/** * Signature help (`lsp.signatureHelp`) while typing call arguments. * * Typing `(` or `,` asks the server for the signatures of the call around * the cursor; while the tooltip is open, every edit and cursor move asks * again (debounced), so the highlighted parameter follows the cursor and * the tooltip closes when the cursor leaves the call (the server returns * no signatures). `Escape` closes it, `Mod-Shift-Space` opens it on * demand. The tooltip shows the active signature with its active * parameter highlighted, a counter when there are several, and the * parameter's and the signature's documentation as safe Markdown. */ import { StateEffect, StateField, type Extension } from "@codemirror/state"; import { EditorView, ViewPlugin, keymap, showTooltip, type PluginValue, type Tooltip, type ViewUpdate, } from "@codemirror/view"; import { t } from "../../../i18n"; import { renderMarkdown } from "./markdown"; import { engineAssistTransport, queryAt } from "./request"; import { toSignatureHelp, type AssistBuffer, type AssistTransport, type SignatureHelpResult } from "./types"; /** Milliseconds between a cursor move or edit and the follow-up request. */ export const SIGNATURE_DEBOUNCE = 120; /** What the tooltip shows, anchored at `pos`. */ export interface SignatureState { /** Where the tooltip is anchored (the cursor when it was asked for). */ pos: number; /** The signatures. */ help: SignatureHelpResult; } /** Sets or clears (null) the shown signature help. */ export const setSignature = StateEffect.define(); /** The shown signature help, mapped through edits. */ export const signatureField = StateField.define({ create: () => null, update(value, tr) { for (const effect of tr.effects) { if (effect.is(setSignature)) { return effect.value; } } if (value && tr.docChanged) { return { pos: tr.changes.mapPos(value.pos), help: value.help }; } return value; }, provide: (field) => showTooltip.from(field, (value): Tooltip | null => value ? { pos: value.pos, above: true, create: (view) => ({ dom: renderSignature(value.help, view.dom.ownerDocument) }), } : null, ), }); /** * Renders signature help. * * @param help - the signatures. * @param owner - the document that creates the nodes. * @returns a `div.lt-assist-signature`. */ export function renderSignature(help: SignatureHelpResult, owner: Document = document): HTMLElement { const root = owner.createElement("div"); root.className = "lt-assist-signature"; const signature = help.signatures[help.activeSignature] ?? help.signatures[0]; if (!signature) { return root; } const head = owner.createElement("div"); head.className = "lt-assist-signature-label"; const active = signature.activeParameter ?? help.activeParameter; const span = signature.parameters[active]?.label ?? null; if (span) { const [from, to] = span; const mark = owner.createElement("span"); mark.className = "lt-assist-signature-active"; mark.textContent = signature.label.slice(from, to); head.append(owner.createTextNode(signature.label.slice(0, from)), mark, owner.createTextNode(signature.label.slice(to))); } else { head.textContent = signature.label; } if (help.signatures.length > 1) { const counter = owner.createElement("span"); counter.className = "lt-assist-signature-count"; counter.textContent = t("editor.assist.signature.count", { index: help.activeSignature + 1, count: help.signatures.length, }); head.prepend(counter); } root.append(head); const parameterDoc = signature.parameters[active]?.documentation; for (const doc of [parameterDoc, signature.documentation]) { if (doc !== undefined) { const dom = renderMarkdown(doc, owner); dom.classList.add("lt-assist-signature-doc"); root.append(dom); } } return root; } /** * Whether an update typed a character that opens or continues an * argument list. * * @param update - the view update. */ export function typedArgumentStart(update: ViewUpdate): boolean { let typed = false; for (const tr of update.transactions) { if (!tr.isUserEvent("input")) { continue; } tr.changes.iterChanges((_fromA, _toA, _fromB, _toB, inserted) => { if (/[(,]$/.test(inserted.toString())) { typed = true; } }); } return typed; } /** The plugin that asks for signature help; see the module docs. */ class SignaturePlugin implements PluginValue { /** The pending debounce timer. */ private timer: ReturnType | null = null; /** Number of the newest request; older answers are dropped. */ private sequence = 0; /** Set once the view is gone. */ private destroyed = false; /** * @param view - the editor view. * @param buffer - the buffer it shows. * @param transport - how to reach the engine. */ constructor( private readonly view: EditorView, private readonly buffer: AssistBuffer, private readonly transport: AssistTransport, ) {} /** Asks again after relevant typing or, while open, any edit or move. */ update(update: ViewUpdate): void { const open = update.state.field(signatureField, false) ?? null; if (typedArgumentStart(update)) { this.schedule(0); } else if (open && (update.docChanged || update.selectionSet)) { this.schedule(SIGNATURE_DEBOUNCE); } } /** * Asks for signature help after `delay` milliseconds. * * @param delay - the debounce. */ schedule(delay: number): void { if (this.timer !== null) { clearTimeout(this.timer); } this.timer = setTimeout(() => { this.timer = null; void this.ask(); }, delay); } /** Sends the request and shows or clears the answer. */ private async ask(): Promise { this.sequence += 1; const sequence = this.sequence; const view = this.view; const pos = view.state.selection.main.head; const value = await queryAt({ buffer: this.buffer, transport: this.transport, doc: view.state.doc, current: () => view.state.doc, pos, command: "lsp.signatureHelp", }); if (this.destroyed || sequence !== this.sequence || view.state.selection.main.head !== pos) { return; } const help = toSignatureHelp(value); const shown = view.state.field(signatureField, false) ?? null; if (!help && !shown) { return; } view.dispatch({ effects: setSignature.of(help ? { pos, help } : null) }); } /** Stops pending work. */ destroy(): void { this.destroyed = true; this.sequence += 1; if (this.timer !== null) { clearTimeout(this.timer); } } } /** The plugins of every signature help extension built so far. */ const plugins = new Set>(); /** * Asks for signature help at the cursor of `view` now. * * @param view - an editor view with the signature help extension. */ export function requestSignatureHelp(view: EditorView): void { for (const plugin of plugins) { const instance = view.plugin(plugin); if (instance) { instance.schedule(0); return; } } } /** * The signature help extension for one buffer. * * @param buffer - the buffer the editor state shows. * @param transport - how to reach the engine. */ export function lspSignatureHelp( buffer: AssistBuffer, transport: AssistTransport = engineAssistTransport, ): Extension { const plugin = ViewPlugin.define((view) => new SignaturePlugin(view, buffer, transport)); plugins.add(plugin); return [ signatureField, plugin, keymap.of([ { key: "Mod-Shift-Space", run: (view) => { view.plugin(plugin)?.schedule(0); return true; }, }, { key: "Escape", run: (view) => { if (!view.state.field(signatureField, false)) { return false; } view.dispatch({ effects: setSignature.of(null) }); return true; }, }, ]), ]; }