дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-04 09:11:10 +02:00
jdtls lists both the keyword interface and a snippet interface that inserts a whole declaration named after the file; picking the snippet while changing class to interface duplicated the declaration. A server snippet whose label matches a keyword in the same list is dropped, as IDEA completes only the keyword. Fixes #7151
1371 рядки
55 KiB
TypeScript
1371 рядки
55 KiB
TypeScript
/**
|
||
* Code completion backed by `lsp_completion`, rendered in IDEA's style: mono
|
||
* rows with a kind letter, the label with the matched prefix emphasised, the
|
||
* label detail, the type right-aligned and a footer hint bar. ↵ inserts, ⇥
|
||
* replaces the rest of the identifier, documentation resolves lazily into the
|
||
* side panel. Without a language server the editor's language-data sources
|
||
* (keywords, local words) are used instead.
|
||
*/
|
||
import {
|
||
acceptCompletion,
|
||
autocompletion,
|
||
closeCompletion,
|
||
completeFromList,
|
||
completionStatus,
|
||
currentCompletions,
|
||
moveCompletionSelection,
|
||
pickedCompletion,
|
||
selectedCompletion,
|
||
startCompletion,
|
||
type Completion,
|
||
type CompletionContext,
|
||
type CompletionInfo,
|
||
type CompletionResult,
|
||
type CompletionSource,
|
||
} from "@codemirror/autocomplete";
|
||
import { EditorSelection, EditorState, Prec, StateEffect, StateField, type Text } from "@codemirror/state";
|
||
import {
|
||
EditorView,
|
||
ViewPlugin,
|
||
getTooltip,
|
||
keymap,
|
||
repositionTooltips,
|
||
showTooltip,
|
||
type Rect,
|
||
type ViewUpdate,
|
||
} from "@codemirror/view";
|
||
import {
|
||
call,
|
||
commands,
|
||
isTauri,
|
||
nextRequestId,
|
||
type CompletionItem,
|
||
type Markup,
|
||
type RequestId,
|
||
} from "@/platform/ipc";
|
||
import { useProject } from "@/platform/project";
|
||
import {
|
||
completionSymbolKind,
|
||
identifierEnd,
|
||
toCmCompletion,
|
||
triggerCharacter,
|
||
typeColumnText,
|
||
withoutDuplicates,
|
||
} from "./completionItems";
|
||
import { applySnippet } from "@/editor/core/cm/linkedSnippet";
|
||
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";
|
||
import { selectableText } from "@/ui/selectableText";
|
||
import { iconNode } from "@/ui/iconNode";
|
||
import { parameterInfoOrLeave, triggerSignatureHelp } from "./signature";
|
||
import { featureBackoff } from "./availability";
|
||
import { pathCompletionSource, pathContext, pathLike } from "./fileReferences";
|
||
import { cssVariablePrefix, cssVariableSource, STYLESHEETS, type VariableOption } from "./cssVariables";
|
||
import { javaDeclarationAt, variableNameSource } from "./variableNames";
|
||
import { editorPrefs } from "@/platform/editorSettings";
|
||
import { tx } from "@/platform/i18n";
|
||
import { showHint } from "./hint";
|
||
import { inplaceRenameActive } from "./inplaceRename";
|
||
import { languageSemantics } from "./semantic";
|
||
import { remoteChange } from "@/editor/api";
|
||
import { tooltipBounds } from "@/editor/core/cm/setup";
|
||
import { completionLabelOffset } from "./theme";
|
||
import { expectedFromSignature, expectedFromText, mentionedNames, smartItems } from "./smartCompletion";
|
||
import { pythonInheritanceGraph } from "@/editor/navigation/inheritanceGraph";
|
||
|
||
interface RequestContext {
|
||
doc: number;
|
||
path: string;
|
||
language: string | null;
|
||
/** Caret offset and document at request time; item ranges refer to these. */
|
||
pos: number;
|
||
text: Text;
|
||
}
|
||
|
||
interface LspCompletion extends Completion {
|
||
lsp: CompletionItem;
|
||
req: RequestContext;
|
||
resolved?: CompletionItem;
|
||
}
|
||
|
||
const isLsp = (c: Completion): c is LspCompletion => "lsp" in c;
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Resolve (documentation, lazily computed edits)
|
||
|
||
const resolving = new WeakMap<CompletionItem, Promise<CompletionItem>>();
|
||
/** Items whose resolve has answered, for accepting them synchronously. */
|
||
const resolvedItems = new WeakMap<CompletionItem, CompletionItem>();
|
||
|
||
function resolveItem(doc: number, item: CompletionItem): Promise<CompletionItem> {
|
||
if (item.data == null && !isEmptyMarkup(item.documentation)) return Promise.resolve(item);
|
||
let p = resolving.get(item);
|
||
if (!p) {
|
||
p = lspRequest(() => commands.lspResolveCompletion(doc, item)).then(
|
||
(r) => {
|
||
if (isEmptyMarkup(r.documentation) && !isEmptyMarkup(item.documentation))
|
||
r = { ...r, documentation: item.documentation };
|
||
resolvedItems.set(item, r);
|
||
return r;
|
||
},
|
||
() => item,
|
||
);
|
||
resolving.set(item, p);
|
||
}
|
||
return p;
|
||
}
|
||
|
||
/**
|
||
* Resolves the selected lookup item ahead of acceptance: some servers compute
|
||
* its extra edits (rust-analyzer's `use` import) only on resolve, against the
|
||
* text as it was, so resolving after the insertion finds nothing.
|
||
*/
|
||
const prefetchResolve = ViewPlugin.fromClass(
|
||
class {
|
||
private last: Completion | null = null;
|
||
update(u: ViewUpdate) {
|
||
const c = selectedCompletion(u.state);
|
||
if (c === this.last) return;
|
||
this.last = c;
|
||
if (c && isLsp(c) && c.lsp.data != null && !c.lsp.additionalEdits.length) void resolveItem(c.req.doc, c.lsp);
|
||
}
|
||
},
|
||
);
|
||
|
||
/**
|
||
* F1 in the lookup (IDEA's documentation popup next to the lookup): docs then
|
||
* follow the selection until the lookup closes. Without the auto-popup setting
|
||
* the info panel waits for this.
|
||
*/
|
||
let docsRequested = false;
|
||
const docWaiters = new Set<() => void>();
|
||
|
||
function renderInfo(c: LspCompletion): Promise<CompletionInfo> {
|
||
const prefs = editorPrefs().completion;
|
||
if (!prefs.showDocumentation && !docsRequested)
|
||
return new Promise((resolve) => {
|
||
const show = () => {
|
||
docWaiters.delete(show);
|
||
resolve(buildInfo(c, 0));
|
||
};
|
||
docWaiters.add(show);
|
||
});
|
||
return buildInfo(c, docsRequested ? 0 : Math.max(0, prefs.documentationDelay));
|
||
}
|
||
|
||
function buildInfo(c: LspCompletion, delay: number): Promise<CompletionInfo> {
|
||
const wait = delay ? new Promise<void>((r) => setTimeout(r, delay)) : Promise.resolve();
|
||
return Promise.all([resolveItem(c.req.doc, c.lsp), wait]).then(([item]) => {
|
||
c.resolved = item;
|
||
const hasDoc = !isEmptyMarkup(item.documentation);
|
||
if (!hasDoc && !item.detail) return null;
|
||
const dom = document.createElement("div");
|
||
dom.className = `cm-lsp-completion-doc ${selectableText}`;
|
||
if (item.detail) dom.appendChild(renderCode(item.detail, c.req.language, "cm-lsp-code cm-lsp-doc-signature"));
|
||
if (hasDoc) dom.appendChild(renderMarkup(item.documentation!, c.req.language));
|
||
return dom;
|
||
});
|
||
}
|
||
|
||
function resetLookupDocs() {
|
||
docsRequested = false;
|
||
docWaiters.clear();
|
||
}
|
||
|
||
const DOC_MIN_WIDTH = 220;
|
||
const DOC_MAX_WIDTH = 440;
|
||
const DOC_MAX_HEIGHT = 320;
|
||
const DOC_GAP = 6;
|
||
|
||
/**
|
||
* Places the documentation beside the lookup, on whichever side has more room,
|
||
* with the two popups' top edges aligned. Room is measured to the window's
|
||
* edges, so a narrow editor still has space for a readable pane; when even the
|
||
* window is too narrow, the pane keeps a readable width rather than covering the
|
||
* options.
|
||
*/
|
||
export function positionCompletionInfo(
|
||
_view: EditorView,
|
||
list: Rect,
|
||
_option: Rect,
|
||
_info: Rect,
|
||
space: Rect,
|
||
): { style: string; class: string } {
|
||
const windowWidth = document.documentElement.clientWidth;
|
||
const rightRoom = windowWidth - list.right - DOC_GAP;
|
||
const leftRoom = list.left - DOC_GAP;
|
||
const side = rightRoom >= leftRoom ? "right" : "left";
|
||
const room = side === "right" ? rightRoom : leftRoom;
|
||
const width = Math.max(DOC_MIN_WIDTH, Math.min(DOC_MAX_WIDTH, room));
|
||
return {
|
||
class: `cm-completionInfo-${side}`,
|
||
style: [
|
||
"top: 0",
|
||
// `left`/`right` names the side the pane sits on; the offset goes on the opposite edge.
|
||
`${side === "right" ? "left" : "right"}: calc(100% + ${DOC_GAP}px)`,
|
||
`max-width: ${width}px`,
|
||
`max-height: ${Math.min(DOC_MAX_HEIGHT, space.bottom - list.top)}px`,
|
||
].join("; "),
|
||
};
|
||
}
|
||
|
||
/**
|
||
* F1 while the lookup is open: shows the selected item's docs beside it
|
||
* (`shown`), or reports that they are already showing (`showing`) so the
|
||
* caller can open them focused instead. `none` without an open lookup.
|
||
*/
|
||
export function showLookupDocs(view: EditorView): "shown" | "showing" | "none" {
|
||
if (completionStatus(view.state) !== "active" || !selectedCompletion(view.state)) return "none";
|
||
if (docsRequested || editorPrefs().completion.showDocumentation) return "showing";
|
||
docsRequested = true;
|
||
for (const show of [...docWaiters]) show();
|
||
return "shown";
|
||
}
|
||
|
||
/** Documentation of the selected lookup item as markup (detail as a code block), or null. */
|
||
export async function selectedLookupDoc(view: EditorView): Promise<{ markup: Markup; language: string | null } | null> {
|
||
const c = selectedCompletion(view.state);
|
||
if (!c || !isLsp(c)) return null;
|
||
const item = await resolveItem(c.req.doc, c.lsp);
|
||
const parts: string[] = [];
|
||
if (item.detail) parts.push("```" + (c.req.language ?? "") + "\n" + item.detail + "\n```");
|
||
if (!isEmptyMarkup(item.documentation)) parts.push(item.documentation!.value);
|
||
return parts.length ? { markup: { kind: "markdown", value: parts.join("\n\n") }, language: c.req.language } : null;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Apply
|
||
|
||
/** Set by the ⇥ binding for the duration of `acceptCompletion`. */
|
||
let replaceMode = false;
|
||
|
||
function applyLsp(view: EditorView, completion: Completion, from: number, to: number) {
|
||
applyLspCompletion(view, completion, from, to, replaceMode ? "replace" : "insert");
|
||
}
|
||
|
||
function completionInsertText(
|
||
item: CompletionItem,
|
||
language: string | null,
|
||
doc: Text,
|
||
from: number,
|
||
to: number,
|
||
): string {
|
||
const { insertText } = item;
|
||
// JDT LS can append a space to a bare annotation name. It is useful only as a separator.
|
||
if (language !== "java" || item.kind !== "interface" || insertText !== `${item.label} `) return insertText;
|
||
const line = doc.lineAt(from);
|
||
const before = line.text.slice(0, from - line.from);
|
||
const after = doc.sliceString(to, to + 2);
|
||
if (!/@(?:[\p{L}\p{N}\p{M}_$]+\.)*$/u.test(before) || identifierEnd(after, 0) > 0) return insertText;
|
||
return item.label;
|
||
}
|
||
|
||
/** ↵ (`insert`) or ⇥ (`replace`: also overwrites the rest of the identifier). */
|
||
export function applyLspCompletion(
|
||
view: EditorView,
|
||
completion: Completion,
|
||
from: number,
|
||
to: number,
|
||
mode: "insert" | "replace",
|
||
) {
|
||
if (!isLsp(completion)) return;
|
||
const { req } = completion;
|
||
const item = completion.resolved ?? resolvedItems.get(completion.lsp) ?? completion.lsp;
|
||
const state = view.state;
|
||
const delta = to - req.pos;
|
||
const mapOld = (offset: number, assoc = 1) =>
|
||
Math.max(
|
||
0,
|
||
Math.min(state.doc.length, offset < req.pos || (offset === req.pos && assoc < 0) ? offset : offset + delta),
|
||
);
|
||
|
||
let start = from;
|
||
let end = to;
|
||
if (item.replaceRange) {
|
||
// An edit requested just after a trigger must include the prefix typed since then.
|
||
start = Math.min(mapOld(posToOffset(req.text, item.replaceRange.start), -1), to);
|
||
end = Math.max(mapOld(posToOffset(req.text, item.replaceRange.end)), to);
|
||
}
|
||
if (mode === "replace") {
|
||
if (item.replaceRangeTab) end = Math.max(end, mapOld(posToOffset(req.text, item.replaceRangeTab.end)));
|
||
else {
|
||
const line = state.doc.lineAt(end);
|
||
end = line.from + identifierEnd(line.text, end - line.from);
|
||
}
|
||
}
|
||
|
||
const extra = textEditsToChanges(req.text, item.additionalEdits)
|
||
.map((c) => ({ from: mapOld(c.from), to: mapOld(c.to), insert: c.insert }))
|
||
.filter((c) => c.to <= start || c.from >= end);
|
||
|
||
const atCarets = applyAtCarets(view, completion, item, start, end, extra);
|
||
if (atCarets) {
|
||
if (item === completion.lsp && !item.additionalEdits.length && item.data != null)
|
||
void applyLateEdits(view, completion, start);
|
||
runCommand(view, item, atCarets === true ? [] : atCarets);
|
||
return;
|
||
}
|
||
|
||
const insertText = completionInsertText(item, req.language, state.doc, start, end);
|
||
let insertedParens: ReturnType<typeof callParens> = null;
|
||
let bareCall: number | null = null;
|
||
if (item.isSnippet) {
|
||
if (extra.length) {
|
||
const tr = state.update({ changes: extra, userEvent: "input.complete" });
|
||
view.dispatch(tr);
|
||
start = tr.changes.mapPos(start, 1);
|
||
end = tr.changes.mapPos(end, 1);
|
||
}
|
||
const source = lspSnippetToCm(insertText, snippetVariables(req.path));
|
||
applySnippet(view, [{ from: start, to: end, snippet: source }], completion);
|
||
// A call snippet without a stop (`ArrayList<>()`): the caret goes inside until
|
||
// signature help says there is nothing to pass.
|
||
const head = view.state.selection.main.head;
|
||
if (
|
||
editorPrefs().completion.insertParentheses &&
|
||
CALLABLE.has(item.kind ?? "") &&
|
||
/\(\)$/.test(item.insertText) &&
|
||
!/\$/.test(item.insertText) &&
|
||
view.state.sliceDoc(head - 2, head) === "()"
|
||
) {
|
||
view.dispatch({ selection: EditorSelection.cursor(head - 1) });
|
||
bareCall = head - 1;
|
||
}
|
||
} else {
|
||
const parens = editorPrefs().completion.insertParentheses
|
||
? callParens(item, state.doc.lineAt(start), start, end)
|
||
: null;
|
||
insertedParens = parens;
|
||
const changes = state.changes([...extra, { from: start, to: end, insert: insertText + (parens ? "()" : "") }]);
|
||
const caret = changes.mapPos(end, 1) - (parens === "inside" ? 1 : 0);
|
||
view.dispatch({
|
||
changes,
|
||
selection: EditorSelection.cursor(caret),
|
||
userEvent: "input.complete",
|
||
annotations: pickedCompletion.of(completion),
|
||
scrollIntoView: true,
|
||
});
|
||
}
|
||
|
||
if (item === completion.lsp && !item.additionalEdits.length && item.data != null)
|
||
void applyLateEdits(view, completion, start);
|
||
// Parameter info for a call left open, plain (`()` added here) or a server snippet (`fly(${1})`).
|
||
const callSnippet = item.isSnippet && CALLABLE.has(item.kind ?? "") && /\(\$\{?\d/.test(item.insertText);
|
||
// Unless the item's command asks for it itself (other commands, like jdtls's
|
||
// `java.completion.onDidSelect`, are bookkeeping).
|
||
const hintsCommand = item.command?.command === "editor.action.triggerParameterHints";
|
||
if ((insertedParens === "inside" || callSnippet) && !hintsCommand) setTimeout(() => triggerSignatureHelp(view), 0);
|
||
else if (bareCall !== null) void parameterInfoOrLeave(view, bareCall);
|
||
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.
|
||
* For an item its server inserts: the other carets the server's edit is to be repeated at.
|
||
*/
|
||
function applyAtCarets(
|
||
view: EditorView,
|
||
completion: LspCompletion,
|
||
item: CompletionItem,
|
||
start: number,
|
||
end: number,
|
||
extra: { from: number; to: number; insert: string }[],
|
||
): boolean | number[] {
|
||
const state = view.state;
|
||
const { ranges, mainIndex } = state.selection;
|
||
if (ranges.length < 2) return false;
|
||
const head = state.selection.main.head;
|
||
// The server inserts the item at the main caret; `caretAfterServerInsert` repeats it at the
|
||
// others that have the same text before them.
|
||
if (serverInserts(item)) {
|
||
const prefix = state.sliceDoc(start, head);
|
||
return ranges
|
||
.filter((r, i) => i !== mainIndex && r.empty && r.head >= prefix.length)
|
||
.filter((r) => state.sliceDoc(r.head - prefix.length, r.head) === prefix)
|
||
.map((r) => r.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;
|
||
|
||
// Parentheses depend on what follows each site: `a.cr|` gets them, `b.cr|()` does not.
|
||
const textAt = (site: { from: number; to: number }): { text: string; caret: number } => {
|
||
const { language, path } = completion.req;
|
||
const insertText = completionInsertText(item, language, state.doc, site.from, site.to);
|
||
if (item.isSnippet) return lspSnippetToPlainWithCaret(insertText, snippetVariables(path));
|
||
const parens = editorPrefs().completion.insertParentheses
|
||
? callParens(item, state.doc.lineAt(site.from), site.from, site.to)
|
||
: null;
|
||
const text = insertText + (parens ? "()" : "");
|
||
return { text, caret: text.length - (parens === "inside" ? 1 : 0) };
|
||
};
|
||
const texts = sites.map(textAt);
|
||
const changes = state.changes([
|
||
...extra,
|
||
...sites.map((site, i) => ({ from: site.from, to: site.to, insert: texts[i]!.text })),
|
||
]);
|
||
const cursors = sites.map((site, i) => EditorSelection.cursor(changes.mapPos(site.from, -1) + texts[i]!.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/;
|
||
|
||
/**
|
||
* Code Completion › Insert parentheses automatically: `()` after a function or
|
||
* method name inserted as plain text (snippets bring their own), with the
|
||
* caret `inside` unless the signature shows no parameters. Null when the
|
||
* name is followed by `(` or an identifier, or names an import.
|
||
*/
|
||
export function callParens(
|
||
item: Pick<CompletionItem, "kind" | "insertText" | "isSnippet" | "labelDetail" | "detail">,
|
||
line: { from: number; text: string },
|
||
start: number,
|
||
end: number,
|
||
): "inside" | "after" | null {
|
||
// An empty text is inserted by the item's server command (kotlin-lsp), parentheses included.
|
||
if (item.isSnippet || !item.kind || !CALLABLE.has(item.kind) || !item.insertText || /[(<[{]/.test(item.insertText))
|
||
return null;
|
||
const next = line.text.charAt(end - line.from);
|
||
if (next && /[(\p{L}\p{N}_$'"`]/u.test(next)) return null;
|
||
if (IMPORT_LINE.test(line.text.slice(0, start - line.from))) return null;
|
||
const sig = item.labelDetail ?? item.detail ?? "";
|
||
return /^\s*\(\s*\)/.test(sig) || /^\s*fn\s*\(\s*\)|^\s*\(\)\s*(=>|->|:)/.test(sig) ? "after" : "inside";
|
||
}
|
||
|
||
/**
|
||
* Some servers (tsserver auto-imports) only compute additional edits on
|
||
* resolve. Apply those that lie before the insertion once they arrive, if the
|
||
* text before it is unchanged.
|
||
*/
|
||
async function applyLateEdits(view: EditorView, c: LspCompletion, insertedAt: number) {
|
||
const item = await resolveItem(c.req.doc, c.lsp);
|
||
if (!item.additionalEdits.length || !view.dom.isConnected) return;
|
||
const edits = textEditsToChanges(c.req.text, item.additionalEdits).filter(
|
||
(e) => e.to <= Math.min(insertedAt, c.req.pos),
|
||
);
|
||
if (!edits.length) return;
|
||
const limit = Math.max(...edits.map((e) => e.to));
|
||
if (view.state.doc.sliceString(0, limit) !== c.req.text.sliceString(0, limit)) return;
|
||
view.dispatch({ changes: edits, userEvent: "input.complete" });
|
||
}
|
||
|
||
/**
|
||
* Where the caret was when an item its server inserts was picked, and the other carets to
|
||
* repeat the edit at, until that edit lands (`null`: none).
|
||
*/
|
||
interface ServerInsert {
|
||
at: number;
|
||
others: readonly number[];
|
||
/** The item is a call that takes arguments: the caret goes inside an inserted `()`. */
|
||
inside?: boolean;
|
||
}
|
||
const awaitServerInsert = StateEffect.define<ServerInsert | null>();
|
||
const serverInsertAt = StateField.define<ServerInsert | null>({
|
||
create: () => null,
|
||
update(value, tr) {
|
||
for (const e of tr.effects) if (e.is(awaitServerInsert)) return e.value;
|
||
// The edit landed, or the caret moved on before it did.
|
||
if (value === null || tr.annotation(remoteChange) || tr.selection) return null;
|
||
return {
|
||
at: tr.changes.mapPos(value.at, -1),
|
||
others: value.others.map((p) => tr.changes.mapPos(p, -1)),
|
||
inside: value.inside,
|
||
};
|
||
},
|
||
});
|
||
|
||
/** The server's edit repeated at other carets: applied as a local edit, so it reaches the document model. */
|
||
const mirrorServerInsert = StateEffect.define<{
|
||
changes: { from: number; to: number; insert: string }[];
|
||
main: number;
|
||
}>();
|
||
const applyServerInsertMirror = EditorView.updateListener.of((u) => {
|
||
for (const tr of u.transactions)
|
||
for (const e of tr.effects) {
|
||
if (!e.is(mirrorServerInsert)) continue;
|
||
const { view } = u;
|
||
const doc = u.state.doc;
|
||
const { changes, main } = e.value;
|
||
queueMicrotask(() => {
|
||
if (!view.dom.isConnected || view.state.doc !== doc) return;
|
||
const mirror = view.state.changes(changes);
|
||
const cursors = [
|
||
{ pos: mirror.mapPos(main, 1), main: true },
|
||
...changes.map((c) => ({ pos: mirror.mapPos(c.from, -1) + c.insert.length, main: false })),
|
||
].sort((a, b) => a.pos - b.pos);
|
||
view.dispatch({
|
||
changes: mirror,
|
||
selection: EditorSelection.create(
|
||
cursors.map((c) => EditorSelection.cursor(c.pos)),
|
||
cursors.findIndex((c) => c.main),
|
||
),
|
||
userEvent: "input.complete",
|
||
});
|
||
});
|
||
}
|
||
});
|
||
|
||
/**
|
||
* The server's edit inserts the item at the caret: the caret goes after it, as after any other
|
||
* completion (a remote insertion at the caret would otherwise leave it in front).
|
||
*/
|
||
const caretAfterServerInsert = EditorState.transactionFilter.of((tr) => {
|
||
const pending = tr.startState.field(serverInsertAt, false);
|
||
const at = pending?.at;
|
||
const caret = tr.startState.selection.main;
|
||
if (
|
||
pending == null ||
|
||
at == null ||
|
||
!tr.docChanged ||
|
||
!tr.annotation(remoteChange) ||
|
||
!caret.empty ||
|
||
caret.head !== at
|
||
)
|
||
return tr;
|
||
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() };
|
||
});
|
||
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 head of pending.others) {
|
||
const from = head - before;
|
||
const to = 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) });
|
||
}
|
||
const inside =
|
||
pending.inside && /\(\)$/.test(landed.insert) && tr.newDoc.sliceString(mainAfter - 2, mainAfter) === "()";
|
||
const selection = EditorSelection.cursor(inside ? mainAfter - 1 : mainAfter);
|
||
if (!others.length) return [tr, { selection, sequential: true }];
|
||
// Not part of this transaction: a remote one is not sent back to the document model.
|
||
const changes = others
|
||
.sort((a, b) => a.from - b.from)
|
||
.map((o) => ({ from: o.from, to: o.to, insert: landed.insert }));
|
||
return [tr, { selection, effects: mirrorServerInsert.of({ changes, main: mainAfter }), 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"]);
|
||
|
||
/** A function or method whose signature lists parameters (`(name: String)`), as far as the item tells. */
|
||
function takesArguments(item: Pick<CompletionItem, "kind" | "labelDetail" | "detail">): boolean {
|
||
if (item.kind && !CALLABLE.has(item.kind)) return false;
|
||
return /^\s*\(\s*[^)\s]/.test(item.labelDetail ?? item.detail ?? "");
|
||
}
|
||
|
||
/** 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, others: readonly number[] = []) {
|
||
const command = item.command;
|
||
if (!command?.command) return;
|
||
const cmd = command.command;
|
||
const serverInserted = serverInserts(item);
|
||
if (serverInserted)
|
||
view.dispatch({
|
||
effects: awaitServerInsert.of({ at: view.state.selection.main.head, others, inside: takesArguments(item) }),
|
||
});
|
||
if (cmd === "editor.action.triggerParameterHints") setTimeout(() => triggerSignatureHelp(view), 0);
|
||
else if (cmd === "editor.action.triggerSuggest") setTimeout(() => startCompletion(view), 0);
|
||
else if (!CLIENT_COMMANDS.has(cmd) && !cmd.startsWith("editor.")) {
|
||
const doc = docOf(view);
|
||
// Server commands (auto-import, postfix…); resulting edits come back as workspace/applyEdit.
|
||
if (doc)
|
||
void lspRequest(() => commands.lspExecuteCommand(doc.doc, command))
|
||
.catch((e: unknown) => reportLspError(view, e, false))
|
||
.finally(() => {
|
||
// The edit arrives before the command's answer; allow for the document update.
|
||
if (serverInserted)
|
||
setTimeout(() => {
|
||
if (view.dom.isConnected && view.state.field(serverInsertAt, false) != null)
|
||
view.dispatch({ effects: awaitServerInsert.of(null) });
|
||
}, SERVER_INSERT_WAIT_MS);
|
||
});
|
||
}
|
||
}
|
||
|
||
const SERVER_INSERT_WAIT_MS = 1000;
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Source
|
||
|
||
const WORD_BEFORE = /[\p{L}\p{N}_$]+$/u;
|
||
const VALID_FOR = /^[\p{L}\p{N}_$]*$/u;
|
||
/** One token a server may replace whole: a Tailwind class (`items-c`), a CSS value. */
|
||
const TOKEN = /^[\p{L}\p{N}_$-]+$/u;
|
||
|
||
/**
|
||
* Start of the token the server replaces, when it reaches back past our word over
|
||
* hyphens (Tailwind's `items-c`). Items from several servers can be merged, so the
|
||
* most common start among single-token ranges ending at the caret wins.
|
||
*/
|
||
function serverTokenStart(items: readonly CompletionItem[], doc: Text, pos: number, wordFrom: number): number | null {
|
||
const votes = new Map<number, number>();
|
||
for (const it of items) {
|
||
if (!it.replaceRange) continue;
|
||
const start = posToOffset(doc, it.replaceRange.start);
|
||
const end = posToOffset(doc, it.replaceRange.end);
|
||
if (start >= wordFrom || end < pos) continue;
|
||
if (!TOKEN.test(doc.sliceString(start, pos))) continue;
|
||
votes.set(start, (votes.get(start) ?? 0) + 1);
|
||
}
|
||
let best: number | null = null;
|
||
let most = 0;
|
||
for (const [start, n] of votes) {
|
||
if (n > most) {
|
||
best = start;
|
||
most = n;
|
||
}
|
||
}
|
||
return best;
|
||
}
|
||
|
||
/**
|
||
* `validFor` for a list that may continue across a hyphen. CodeMirror re-queries
|
||
* when this returns false, so only keep the list while an option still starts
|
||
* with the typed text: `items-` continues (Tailwind), `foo-bar` in JS re-queries.
|
||
* A list pruned for a longer token is only valid while the text still starts
|
||
* with that token, so backspacing asks the server again.
|
||
*/
|
||
export function completionValidFor(items: readonly CompletionItem[], prunedBy: string | null) {
|
||
let labels: string[] | null = null; // built lazily: an explicit list can hold 26k items
|
||
return (text: string): boolean => {
|
||
const typed = text.toLowerCase();
|
||
if (prunedBy && !typed.startsWith(prunedBy)) return false;
|
||
if (VALID_FOR.test(text)) return true;
|
||
if (!text.includes("-") || !TOKEN.test(text)) return false;
|
||
labels ??= items.map((it) => (it.filterText ?? it.label).toLowerCase());
|
||
return labels.some((label) => label.startsWith(typed));
|
||
};
|
||
}
|
||
|
||
// Above this, mapping every item to a CodeMirror option and re-filtering it on each
|
||
// keystroke shows up as input lag (Tailwind sends ~26k); below it pruning isn't worth it.
|
||
const PRUNE_ABOVE = 2000;
|
||
|
||
function isSubsequence(needle: string, haystack: string): boolean {
|
||
let at = 0;
|
||
for (const ch of haystack) if (ch === needle[at] && ++at === needle.length) return true;
|
||
return at === needle.length;
|
||
}
|
||
|
||
/**
|
||
* Items that can still match `typed`. Subsequence accepts a superset of what the
|
||
* fuzzy matcher shows for longer text, so typing on loses nothing. `prunedBy` is
|
||
* set only when something was dropped.
|
||
*/
|
||
export function pruneItems(
|
||
items: readonly CompletionItem[],
|
||
typed: string,
|
||
): { items: readonly CompletionItem[]; prunedBy: string | null } {
|
||
if (!typed || items.length <= PRUNE_ABOVE) return { items, prunedBy: null };
|
||
const needle = typed.toLowerCase();
|
||
const kept = items.filter((it) => isSubsequence(needle, (it.filterText ?? it.label).toLowerCase()));
|
||
return kept.length && kept.length < items.length ? { items: kept, prunedBy: needle } : { items, prunedBy: null };
|
||
}
|
||
|
||
let inflight: RequestId | null = null;
|
||
|
||
function cancelInflight() {
|
||
if (inflight !== null && isTauri()) void commands.cancelRequest(inflight);
|
||
inflight = null;
|
||
}
|
||
|
||
/** Inside a stylesheet's `var(`, where `cssVariableSource` lists the project's custom properties instead of the server or the document's words. */
|
||
function inVarCall(ctx: CompletionContext): boolean {
|
||
const language = ctx.state.facet(lspDoc)?.language ?? "";
|
||
if (!STYLESHEETS.has(language) || !isTauri()) return false;
|
||
const line = ctx.state.doc.lineAt(ctx.pos);
|
||
return cssVariablePrefix(line.text.slice(0, ctx.pos - line.from)) !== null;
|
||
}
|
||
|
||
/** Language-data completion sources (keywords etc.), used when no server answers. */
|
||
async function fallback(ctx: CompletionContext): Promise<CompletionResult | null> {
|
||
if (inVarCall(ctx)) return null;
|
||
const sources = ctx.state.languageDataAt<CompletionSource | readonly (string | Completion)[]>(
|
||
"autocomplete",
|
||
ctx.pos,
|
||
);
|
||
for (const s of sources) {
|
||
const source = typeof s === "function" ? s : completeFromList(s);
|
||
// oxlint-disable-next-line no-await-in-loop -- falls back to the next source only when this one has no result; first answer wins
|
||
const r = await source(ctx);
|
||
if (r) return r;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
export function makeCompletion(item: CompletionItem, req: RequestContext): LspCompletion {
|
||
if (item.kind === "keyword" && isEmptyMarkup(item.documentation)) {
|
||
const value = languageSemantics(req.language)?.constructDocumentation?.(item.label);
|
||
if (value) item = { ...item, documentation: { kind: "markdown", value } };
|
||
}
|
||
// The lookup handles commit characters itself (focused lookups only, see `lookupKeys`).
|
||
const { commitCharacters: _server, ...cm } = toCmCompletion(item);
|
||
return Object.assign(cm, {
|
||
lsp: item,
|
||
req,
|
||
// CodeMirror merges options with the same label, detail and `apply`: overloads
|
||
// sharing a filterText (`times(other: Int)`, `times(other: Long)`…) and the same
|
||
// name imported from different modules need their own. A Java type's package is
|
||
// shown in the type column (`labelDescription` / `detail`), not CodeMirror's
|
||
// `detail`, and JDT.LS often defers the import edit until resolve — without a
|
||
// distinct apply, only one of those candidates is listed.
|
||
apply:
|
||
cm.displayLabel ||
|
||
(item.filterText && item.filterText !== item.label) ||
|
||
item.additionalEdits.length ||
|
||
item.labelDescription ||
|
||
item.detail ||
|
||
item.labelDetail
|
||
? (...a: Parameters<typeof applyLsp>) => applyLsp(...a)
|
||
: applyLsp,
|
||
info: (c: Completion) => renderInfo(c as LspCompletion),
|
||
});
|
||
}
|
||
|
||
/**
|
||
* Sources other features contribute via the `openideaCompletion` language-data
|
||
* key (live templates, postfix, SQL). Results starting where the first one
|
||
* does are merged into one list. Options may carry `icon` (an icon name, `null`
|
||
* for none) and `typeText` (the right-aligned type column), like LSP items.
|
||
*/
|
||
const contributedSource: CompletionSource = async (ctx) => {
|
||
const sources = ctx.state.languageDataAt<CompletionSource>("openideaCompletion", ctx.pos);
|
||
const answers = await Promise.all(sources.map((source) => source(ctx)));
|
||
const results = answers.filter((r): r is CompletionResult => !!r);
|
||
return mergeResults(results);
|
||
};
|
||
|
||
export function mergeResults(results: readonly CompletionResult[]): CompletionResult | null {
|
||
const [first] = results;
|
||
if (!first || results.length === 1) return first ?? null;
|
||
const same = results.filter((r) => r.from === first.from);
|
||
const validFor = same.every(
|
||
(r) => r.validFor instanceof RegExp && r.validFor.source === (first.validFor as RegExp | undefined)?.source,
|
||
)
|
||
? first.validFor
|
||
: undefined;
|
||
return { from: first.from, to: first.to, options: same.flatMap((r) => r.options), validFor };
|
||
}
|
||
|
||
/** Rendering extras of contributed (non-LSP) options. */
|
||
interface RichCompletion extends Completion {
|
||
icon?: string | null;
|
||
typeText?: string;
|
||
}
|
||
|
||
/** Documents the server could not complete in, so typing doesn't ask again until a server is ready. */
|
||
const completionBackoff = featureBackoff();
|
||
|
||
async function lspCompletionSource(ctx: CompletionContext): Promise<CompletionResult | null> {
|
||
const doc = ctx.state.facet(lspDoc);
|
||
if (!doc || doc.readOnly) return null;
|
||
const word = ctx.matchBefore(WORD_BEFORE);
|
||
const trigger = triggerCharacter(ctx.state.sliceDoc(Math.max(0, ctx.pos - 128), ctx.pos), doc.language);
|
||
if (!ctx.explicit && !word && !trigger) return null;
|
||
if (!ctx.explicit && word && !trigger && /^\d/.test(word.text)) return null;
|
||
const smart = ctx.state.field(smartLookup, false) ?? false;
|
||
if (!ctx.explicit && completionBackoff.active(doc.doc)) return smart ? null : fallback(ctx);
|
||
cancelInflight();
|
||
const id = nextRequestId();
|
||
inflight = id;
|
||
ctx.addEventListener("abort", () => {
|
||
if (inflight === id) cancelInflight();
|
||
});
|
||
let list;
|
||
try {
|
||
list = await lspRequest(
|
||
() => commands.lspCompletion(id, doc.doc, offsetToPos(ctx.state.doc, ctx.pos), trigger),
|
||
() => inflight === id,
|
||
);
|
||
completionBackoff.clear(doc.doc);
|
||
} catch (e) {
|
||
if (isUnavailable(e)) {
|
||
completionBackoff.mark(doc.doc);
|
||
return smart ? null : fallback(ctx);
|
||
}
|
||
return null;
|
||
} finally {
|
||
if (inflight === id) inflight = null;
|
||
}
|
||
if (ctx.aborted || !list.items.length) return list.items.length || smart ? null : fallback(ctx);
|
||
const wordFrom = word?.from ?? ctx.pos;
|
||
// Tailwind's replace range covers the whole class (`items-c`) while our word is
|
||
// only the `c` after the hyphen; CodeMirror matches a one-character pattern only
|
||
// at the start of a label, so filtering on `c` drops `items-center`.
|
||
const completionFrom = serverTokenStart(list.items, ctx.state.doc, ctx.pos, wordFrom) ?? wordFrom;
|
||
const typed = ctx.state.sliceDoc(completionFrom, ctx.pos);
|
||
let lower: ReadonlySet<CompletionItem> = new Set();
|
||
if (smart) {
|
||
const expected = await expectedType(ctx, doc.doc, word?.from ?? ctx.pos);
|
||
if (ctx.aborted) return null;
|
||
if (!expected) {
|
||
smartHint(ctx, tx("No expected type at the caret"));
|
||
return null;
|
||
}
|
||
const from = word?.from ?? ctx.pos;
|
||
const graph = doc.language === "python" ? await pythonInheritanceGraph().catch(() => []) : [];
|
||
const bases = new Map<string, string[]>();
|
||
for (const c of graph) bases.set(c.name, [...(bases.get(c.name) ?? []), ...c.bases]);
|
||
const smartResult = await smartItems(list.items, expected, (item) => resolveItem(doc.doc, item), {
|
||
typed,
|
||
member: ctx.state.sliceDoc(from - 1, from) === ".",
|
||
mentioned: mentionedNames(ctx.state.doc.toString()),
|
||
bases: (name) => bases.get(name) ?? [],
|
||
aborted: () => ctx.aborted,
|
||
});
|
||
if (ctx.aborted) return null;
|
||
list = { ...list, items: smartResult.items };
|
||
lower = smartResult.lower;
|
||
if (!list.items.length) {
|
||
smartHint(ctx, tx`No suggestions of type ${expected}`);
|
||
return null;
|
||
}
|
||
}
|
||
const req: RequestContext = { doc: doc.doc, path: doc.path, language: doc.uiMode, pos: ctx.pos, text: ctx.state.doc };
|
||
const prefs = editorPrefs().completion;
|
||
let items = withoutDuplicates(
|
||
prefs.matchCase
|
||
? list.items.filter((it) => matchesCase(it.filterText ?? it.label, typed, prefs.caseSensitivity))
|
||
: list.items,
|
||
);
|
||
if (inVarCall(ctx)) items = items.filter((it) => !it.label.startsWith("--"));
|
||
const pruned = pruneItems(items, typed);
|
||
items = [...pruned.items];
|
||
// A server snippet named like a keyword it also lists (jdtls `interface`, `class`, `enum` declaration
|
||
// skeletons) would replace one word with a whole declaration; IDEA completes the keyword.
|
||
const keywords = new Set(items.filter((it) => it.kind === "keyword").map((it) => it.label));
|
||
if (keywords.size) items = items.filter((it) => it.kind !== "snippet" || !keywords.has(it.label));
|
||
// A server snippet named like a live template (jdtls `sout`, `fori`) would be listed twice; the template wins.
|
||
if (items.some((it) => it.kind === "snippet")) {
|
||
const own = await contributedSource(ctx);
|
||
if (ctx.aborted) return null;
|
||
const names = new Set(own?.options.map((o) => o.label));
|
||
if (names.size) items = items.filter((it) => it.kind !== "snippet" || !names.has(it.label));
|
||
}
|
||
return {
|
||
from: completionFrom,
|
||
options: items.map((item) => {
|
||
const option = makeCompletion(item, req);
|
||
// Smart Type: an item that may fit (`Any`) follows the ones that do.
|
||
if (lower.has(item)) option.boost = -10;
|
||
return option;
|
||
}),
|
||
// "All letters" must re-check case on every keystroke; Smart Type resolved only what matched the typed letters.
|
||
validFor:
|
||
list.isIncomplete || (prefs.matchCase && prefs.caseSensitivity === "all") || (smart && typed)
|
||
? undefined
|
||
: completionValidFor(items, pruned.prunedBy),
|
||
filter: true,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Code Completion › Sort suggestions alphabetically: the source's options are
|
||
* filtered here (prefix, substring, then subsequence) and listed by name;
|
||
* typing on re-filters the same options while the source's `validFor` holds.
|
||
*/
|
||
export function sortAlphabetically(result: CompletionResult, typed: string): CompletionResult {
|
||
if (result.filter === false) return result;
|
||
const matched = new Map<Completion, readonly number[]>();
|
||
for (const o of result.options) {
|
||
const m = matchRanges(o.label, typed);
|
||
if (m) matched.set(o, o.displayLabel ? [] : m);
|
||
}
|
||
const name = (c: Completion) => c.displayLabel ?? c.label;
|
||
const options = [...matched.keys()].sort(
|
||
(a, b) => name(a).localeCompare(name(b), undefined, { sensitivity: "base" }) || name(a).localeCompare(name(b)),
|
||
);
|
||
const { validFor } = result;
|
||
return {
|
||
from: result.from,
|
||
to: result.to,
|
||
options,
|
||
filter: false,
|
||
getMatch: (c) => matched.get(c) ?? [],
|
||
update: validFor
|
||
? (_cur, from, to, ctx) => {
|
||
const text = ctx.state.sliceDoc(from, to);
|
||
const ok =
|
||
typeof validFor === "function"
|
||
? validFor(text, from, to, ctx.state)
|
||
: new RegExp(`^(?:${validFor.source})$`, validFor.flags).test(text);
|
||
return ok ? sortAlphabetically({ ...result, from }, text) : null;
|
||
}
|
||
: undefined,
|
||
};
|
||
}
|
||
|
||
/** Matched ranges of `typed` in `label`, ignoring case: a substring, else a subsequence; null without a match. */
|
||
export function matchRanges(label: string, typed: string): number[] | null {
|
||
if (!typed) return [];
|
||
const lower = label.toLowerCase();
|
||
const p = typed.toLowerCase();
|
||
const at = lower.indexOf(p);
|
||
if (at >= 0) return [at, at + p.length];
|
||
const ranges: number[] = [];
|
||
let i = 0;
|
||
for (let j = 0; j < lower.length && i < p.length; j++) {
|
||
if (lower[j] !== p[i]) continue;
|
||
if (ranges.length && ranges[ranges.length - 1] === j) ranges[ranges.length - 1] = j + 1;
|
||
else ranges.push(j, j + 1);
|
||
i++;
|
||
}
|
||
return i === p.length ? ranges : null;
|
||
}
|
||
|
||
/** Code Completion › Match case: first letter only, or every typed letter (as a subsequence). */
|
||
export function matchesCase(label: string, typed: string, mode: string): boolean {
|
||
if (!typed) return true;
|
||
if (mode !== "all") {
|
||
const first = typed[0]!;
|
||
const head = label[0] ?? "";
|
||
return head.toLowerCase() !== first.toLowerCase() || head === first;
|
||
}
|
||
let i = 0;
|
||
for (const ch of label) if (ch === typed[i]) i++;
|
||
return i >= typed.length;
|
||
}
|
||
|
||
/**
|
||
* A source another feature restricts the lookup to, via the
|
||
* `openideaExclusiveCompletion` language-data key (`(state) => source | null`;
|
||
* ⌘J's live templates).
|
||
*/
|
||
function exclusiveSource(ctx: CompletionContext): CompletionSource | null {
|
||
type Provider = (state: CompletionContext["state"]) => CompletionSource | null;
|
||
for (const f of ctx.state.languageDataAt<Provider>("openideaExclusiveCompletion", ctx.pos)) {
|
||
const source = f(ctx.state);
|
||
if (source) return source;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* Smart Type completion: while its lookup is open, the language server's items are narrowed to
|
||
* the caret's expected type and the other sources stay out.
|
||
*/
|
||
const setSmartLookup = StateEffect.define<boolean>();
|
||
const smartLookup = StateField.define<boolean>({
|
||
create: () => false,
|
||
update: (value, tr) => tr.effects.reduce((v, e) => (e.is(setSmartLookup) ? e.value : v), value),
|
||
});
|
||
|
||
/** Ends Smart Type mode when its lookup closes or finds nothing. */
|
||
const endSmartLookup = EditorView.updateListener.of((u) => {
|
||
if (!u.state.field(smartLookup) || completionStatus(u.startState) === null || completionStatus(u.state) !== null)
|
||
return;
|
||
queueMicrotask(() => {
|
||
if (u.view.state.field(smartLookup) && completionStatus(u.view.state) === null)
|
||
u.view.dispatch({ effects: setSmartLookup.of(false) });
|
||
});
|
||
});
|
||
|
||
/** The type expected at `from`: an annotated assignment, a `return`, else the active parameter's. */
|
||
async function expectedType(ctx: CompletionContext, doc: number, from: number): Promise<string | null> {
|
||
const fromText = expectedFromText(ctx.state, from);
|
||
if (fromText) return fromText;
|
||
const help = await lspRequest(() => commands.lspSignatureHelp(doc, offsetToPos(ctx.state.doc, from))).catch(
|
||
() => null,
|
||
);
|
||
return expectedFromSignature(help);
|
||
}
|
||
|
||
/** Says why the Smart Type lookup is empty, in place of the generic "No suggestions". */
|
||
function smartHint(ctx: CompletionContext, text: string) {
|
||
if (!ctx.view) return;
|
||
explicitPending.delete(ctx.view);
|
||
showHint(ctx.view, text, { timeout: 2000 });
|
||
}
|
||
|
||
/** ⌃Space: Basic completion, leaving Smart Type mode as IDEA does. */
|
||
export function basicCompletion(view: EditorView): boolean {
|
||
if (view.state.field(smartLookup, false)) view.dispatch({ effects: setSmartLookup.of(false) });
|
||
return explicitCompletion(view);
|
||
}
|
||
|
||
/** ⌃⇧Space: the lookup lists only what fits the expected type at the caret. */
|
||
export function smartTypeCompletion(view: EditorView): boolean {
|
||
closeCompletion(view);
|
||
view.dispatch({ effects: setSmartLookup.of(true) });
|
||
const started = explicitCompletion(view);
|
||
if (!started) view.dispatch({ effects: setSmartLookup.of(false) });
|
||
return started;
|
||
}
|
||
|
||
/** Show suggestions as you type: sources only answer explicit requests when it is off. */
|
||
function gated(source: CompletionSource): CompletionSource {
|
||
return (ctx) => {
|
||
if (ctx.state.field(smartLookup, false) && source !== claimingLspSource) return null;
|
||
const only = exclusiveSource(ctx);
|
||
if (only) return source === contributedSource ? only(ctx) : null;
|
||
// At a Java declaration's name only names fit: IDEA lists no live templates there, and
|
||
// jdtls' own name proposals repeat the type (`orderBookOrderBook`).
|
||
if (source !== variableNameSource && javaDeclarationAt(ctx)) return null;
|
||
if (!ctx.explicit && (!editorPrefs().completion.autoPopup || inplaceRenameActive(ctx.state))) return null;
|
||
if (!editorPrefs().completion.sortAlphabetically) return source(ctx);
|
||
return Promise.resolve(source(ctx)).then(
|
||
(r) => r && sortAlphabetically(r, ctx.state.sliceDoc(r.from, r.to ?? ctx.pos)),
|
||
);
|
||
};
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Lookup focus, commit characters, explicit invocation
|
||
|
||
/**
|
||
* As in IDEA, these finish a *focused* lookup with the selected
|
||
* item before being typed; an unfocused auto-popup just
|
||
* closes on them unless Settings › Code Completion › "Insert selected
|
||
* suggestion by pressing space, dot…" is on.
|
||
*/
|
||
export const COMMIT_CHARS = [".", ",", ";", "=", " ", ":", "("];
|
||
|
||
/** Lookups the user engaged with: opened explicitly (⌃Space) or navigated with ↑/↓. */
|
||
const focusedLookups = new WeakSet<EditorView>();
|
||
/** Explicit invocations waiting for their first result (single candidate → insert it). */
|
||
const explicitPending = new WeakSet<EditorView>();
|
||
|
||
const NAVIGATION_KEYS = new Set(["ArrowUp", "ArrowDown", "PageUp", "PageDown"]);
|
||
|
||
/** Whether typing `ch` finishes the open lookup with its selected item. */
|
||
export function commitsLookup(
|
||
ch: string,
|
||
focused: boolean,
|
||
insertOnSpecialKeys: boolean,
|
||
itemChars: readonly string[] = [],
|
||
): boolean {
|
||
if (!focused && !insertOnSpecialKeys) return false;
|
||
return COMMIT_CHARS.includes(ch) || itemChars.includes(ch);
|
||
}
|
||
|
||
const lookupKeys = Prec.highest(
|
||
EditorView.domEventHandlers({
|
||
keydown(e, view) {
|
||
if (e.isComposing || completionStatus(view.state) !== "active") return false;
|
||
if (NAVIGATION_KEYS.has(e.key) && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
||
focusedLookups.add(view);
|
||
return false;
|
||
}
|
||
if (e.key.length !== 1 || e.metaKey || e.ctrlKey || e.altKey) return false;
|
||
const selected = selectedCompletion(view.state);
|
||
if (!selected) return false;
|
||
const itemChars = isLsp(selected) ? selected.lsp.commitCharacters : (selected.commitCharacters ?? []);
|
||
if (!commitsLookup(e.key, focusedLookups.has(view), editorPrefs().completion.insertOnSpecialKeys, itemChars))
|
||
return false;
|
||
if (!acceptCompletion(view)) return false;
|
||
// A call snippet or inserted parentheses already opened the call: the typed one is consumed.
|
||
const head = view.state.selection.main.head;
|
||
if (
|
||
e.key === "(" &&
|
||
(view.state.sliceDoc(head - 1, head) === "(" || view.state.sliceDoc(head - 2, head) === "()")
|
||
) {
|
||
e.preventDefault();
|
||
return true;
|
||
}
|
||
return false;
|
||
},
|
||
}),
|
||
);
|
||
|
||
function moveLookup(view: EditorView, forward: boolean): boolean {
|
||
if (completionStatus(view.state) !== "active") return false;
|
||
focusedLookups.add(view);
|
||
return moveCompletionSelection(forward)(view);
|
||
}
|
||
|
||
/** IDEA inserts a sole candidate right away on explicit invocation (Code Completion › Automatically insert single suggestions). */
|
||
const AUTO_INSERT_DELAY = 80; // past CodeMirror's interactionDelay
|
||
|
||
const lookupTracker = ViewPlugin.fromClass(
|
||
class {
|
||
private prev: ReturnType<typeof completionStatus> = null;
|
||
constructor(private view: EditorView) {}
|
||
update(u: ViewUpdate) {
|
||
const status = completionStatus(u.state);
|
||
const prev = this.prev;
|
||
this.prev = status;
|
||
if (status === prev && status !== "active") return;
|
||
const view = this.view;
|
||
if (status === null) {
|
||
focusedLookups.delete(view);
|
||
resetLookupDocs();
|
||
if (explicitPending.has(view)) {
|
||
explicitPending.delete(view);
|
||
if (prev === "pending" && !u.docChanged)
|
||
queueMicrotask(() => showHint(view, "No suggestions", { timeout: 2000 }));
|
||
}
|
||
} else if (status === "active" && explicitPending.has(view)) {
|
||
explicitPending.delete(view);
|
||
const options = currentCompletions(u.state);
|
||
if (options.length === 1 && editorPrefs().completion.autoInsertSingle) {
|
||
const doc = u.state.doc;
|
||
setTimeout(() => {
|
||
const state = view.state;
|
||
const now = currentCompletions(state);
|
||
const { head } = state.selection.main;
|
||
const line = state.doc.lineAt(head);
|
||
const column = head - line.from;
|
||
// Keep the lookup open so Tab can replace the remaining identifier.
|
||
if (
|
||
state.doc === doc &&
|
||
completionStatus(state) === "active" &&
|
||
now.length === 1 &&
|
||
now[0] === options[0] &&
|
||
identifierEnd(line.text, column) === column
|
||
)
|
||
acceptCompletion(view);
|
||
}, AUTO_INSERT_DELAY);
|
||
}
|
||
}
|
||
}
|
||
},
|
||
);
|
||
|
||
/** ⌃Space: explicit completion with a focused lookup. */
|
||
export function explicitCompletion(view: EditorView): boolean {
|
||
explicitPending.add(view);
|
||
const started = startCompletion(view);
|
||
if (!started) explicitPending.delete(view);
|
||
else focusedLookups.add(view);
|
||
return started;
|
||
}
|
||
|
||
// ---------------------------------------------------------------------------
|
||
// Rendering
|
||
|
||
function kindBadge(c: Completion): Node | null {
|
||
const swatch = (c as VariableOption).swatch;
|
||
if (swatch) {
|
||
const span = document.createElement("span");
|
||
span.className = "cm-lsp-kind cm-lsp-swatch";
|
||
span.style.setProperty("--swatch", swatch);
|
||
return span;
|
||
}
|
||
if (!isLsp(c) && "icon" in c) {
|
||
const icon = (c as RichCompletion).icon;
|
||
if (icon) return iconNode(icon, 16, "cm-lsp-kind");
|
||
const blank = document.createElement("span");
|
||
blank.className = "cm-lsp-kind";
|
||
return blank;
|
||
}
|
||
const kind = isLsp(c) ? completionSymbolKind(c.lsp.kind) : (c.type ?? "text");
|
||
const span = iconNode(`symbol-${kind}`, 16, "cm-lsp-kind");
|
||
span.dataset.kind = kind;
|
||
return span;
|
||
}
|
||
|
||
function typeColumn(c: Completion): Node | null {
|
||
const detail = isLsp(c) ? typeColumnText(c.lsp) : (c as RichCompletion).typeText?.replace(/\s+/g, " ");
|
||
if (!detail) return null;
|
||
const span = document.createElement("span");
|
||
span.className = "cm-lsp-type";
|
||
span.textContent = detail;
|
||
return span;
|
||
}
|
||
|
||
/** Toggles Code Completion › Sort suggestions alphabetically (globally) and re-opens the lookup. */
|
||
async function toggleSortByName(view: EditorView) {
|
||
const on = !editorPrefs().completion.sortAlphabetically;
|
||
if (isTauri()) {
|
||
const settings = await call(
|
||
commands.settingsSet("global", "editor.completion.sortAlphabetically", JSON.stringify(on)),
|
||
);
|
||
useProject.setState({ settings });
|
||
}
|
||
if (!view.dom.isConnected) return;
|
||
closeCompletion(view);
|
||
startCompletion(view);
|
||
}
|
||
|
||
function sortToggle(view: EditorView): HTMLElement {
|
||
const button = document.createElement("button");
|
||
button.type = "button";
|
||
button.className = "cm-lsp-completion-sort";
|
||
button.textContent = tx("Sort by name");
|
||
const on = editorPrefs().completion.sortAlphabetically;
|
||
button.setAttribute("aria-pressed", String(on));
|
||
button.title = tx(on ? "Sort suggestions by relevance" : "Sort suggestions alphabetically");
|
||
// Keep the editor focused so the lookup survives the click.
|
||
button.addEventListener("mousedown", (e) => e.preventDefault());
|
||
button.addEventListener("click", () => void toggleSortByName(view).catch(() => {}));
|
||
return button;
|
||
}
|
||
|
||
const completionPopup = ViewPlugin.fromClass(
|
||
class {
|
||
constructor(private view: EditorView) {}
|
||
update(u: ViewUpdate) {
|
||
// The lookup can show partial results while another source is still pending.
|
||
const popup = u.state
|
||
.facet(showTooltip)
|
||
.map((tooltip) => tooltip && getTooltip(this.view, tooltip))
|
||
.find((tooltip) => tooltip?.dom.classList.contains("cm-lsp-completion"));
|
||
if (!popup) return;
|
||
popup.offset ??= { x: -completionLabelOffset, y: 0 };
|
||
const t = popup.dom;
|
||
this.view.requestMeasure({
|
||
key: this,
|
||
read: () => {
|
||
const { left, right } = tooltipBounds(this.view);
|
||
return {
|
||
width: `${Math.max(0, Math.floor(right - left))}px`,
|
||
fontSize: getComputedStyle(this.view.contentDOM).fontSize,
|
||
};
|
||
},
|
||
write: ({ width, fontSize }) => {
|
||
if (!t.isConnected) return;
|
||
const widthChanged = t.style.getPropertyValue("--cm-completion-max-width") !== width;
|
||
if (widthChanged) t.style.setProperty("--cm-completion-max-width", width);
|
||
// The body-level tooltip does not inherit the editor's temporary font zoom.
|
||
const fontChanged = t.style.getPropertyValue("--openidea-editor-font-size") !== fontSize;
|
||
if (fontChanged) t.style.setProperty("--openidea-editor-font-size", fontSize);
|
||
let footer = t.querySelector<HTMLElement>(":scope > .cm-lsp-completion-footer");
|
||
if (!footer) {
|
||
footer = document.createElement("div");
|
||
footer.className = "cm-lsp-completion-footer";
|
||
const tip = document.createElement("span");
|
||
tip.textContent = tx("Press ↵ to insert, ⇥ to replace");
|
||
tip.title = tip.textContent;
|
||
footer.append(tip, sortToggle(this.view));
|
||
}
|
||
// CodeMirror appends a fresh list when the candidates change.
|
||
const list = t.querySelector(":scope > ul");
|
||
const footerMoved = list && list.nextElementSibling !== footer;
|
||
if (footerMoved) list.after(footer);
|
||
// CodeMirror has already measured the lookup. Reposition it before this frame paints.
|
||
if (widthChanged || fontChanged || footerMoved) repositionTooltips(this.view);
|
||
},
|
||
});
|
||
}
|
||
},
|
||
);
|
||
|
||
let pluginClaim: { pos: number; claimed: Promise<boolean> } | null = null;
|
||
|
||
const claimingLspSource: CompletionSource = (ctx) => {
|
||
const result = Promise.resolve(lspCompletionSource(ctx));
|
||
pluginClaim = {
|
||
pos: ctx.pos,
|
||
claimed: result.then((r) => !!r?.options.some((o) => isLsp(o) && o.lsp.server === 0)).catch(() => false),
|
||
};
|
||
return result;
|
||
};
|
||
|
||
const PATH_ONLY_WHEN_PATH_LIKE = new Set(["php", "blade"]);
|
||
|
||
export function offersPaths(language: string, before: string): boolean {
|
||
if (!PATH_ONLY_WHEN_PATH_LIKE.has(language)) return true;
|
||
const found = pathContext(before, language);
|
||
return !!found && pathLike(found.prefix);
|
||
}
|
||
|
||
const pathFallbackSource: CompletionSource = async (ctx) => {
|
||
const line = ctx.state.doc.lineAt(ctx.pos);
|
||
if (!offersPaths(ctx.state.facet(lspDoc)?.language ?? "", line.text.slice(0, ctx.pos - line.from))) return null;
|
||
const claim = pluginClaim;
|
||
if (claim && claim.pos === ctx.pos && (await claim.claimed)) return null;
|
||
return pathCompletionSource(ctx);
|
||
};
|
||
|
||
export function completionExtension() {
|
||
return [
|
||
lookupKeys,
|
||
prefetchResolve,
|
||
smartLookup,
|
||
endSmartLookup,
|
||
autocompletion({
|
||
override: [
|
||
gated(claimingLspSource),
|
||
gated(contributedSource),
|
||
gated(pathFallbackSource),
|
||
gated(cssVariableSource),
|
||
gated(variableNameSource),
|
||
],
|
||
icons: false,
|
||
addToOptions: [
|
||
{ render: kindBadge, position: 20 },
|
||
{ render: typeColumn, position: 90 },
|
||
],
|
||
optionClass: (c) => {
|
||
// IDEA shows keywords in bold.
|
||
const keyword = (isLsp(c) ? c.lsp.kind : c.type) === "keyword" ? " cm-lsp-keyword-option" : "";
|
||
return (
|
||
(isLsp(c) ? (c.lsp.deprecated ? "cm-lsp-option cm-lsp-deprecated-option" : "cm-lsp-option") : "") + keyword
|
||
);
|
||
},
|
||
tooltipClass: () => "cm-lsp-completion",
|
||
positionInfo: positionCompletionInfo,
|
||
}),
|
||
completionPopup,
|
||
lookupTracker,
|
||
serverInsertAt,
|
||
caretAfterServerInsert,
|
||
applyServerInsertMirror,
|
||
Prec.highest(
|
||
keymap.of([
|
||
// macOS: ⌃N / ⌃P are line down / up in text, so they move through the lookup as ↓ / ↑ do.
|
||
{ mac: "Ctrl-n", run: (view) => moveLookup(view, true) },
|
||
{ mac: "Ctrl-p", run: (view) => moveLookup(view, false) },
|
||
{
|
||
key: "Tab",
|
||
run: (view) => {
|
||
if (completionStatus(view.state) !== "active") return false;
|
||
replaceMode = true;
|
||
try {
|
||
return acceptCompletion(view);
|
||
} finally {
|
||
replaceMode = false;
|
||
}
|
||
},
|
||
},
|
||
]),
|
||
),
|
||
];
|
||
}
|
||
|
||
export { startCompletion };
|