Sub topic 7
Writing a completion provider in an editor extension
An editor extension turns a model into ghost text by registering a provider with the editor. The editor calls the provider when a suggestion might be needed. The provider returns text, and the editor draws and accepts it. This chapter builds that provider for VS Code in TypeScript. JetBrains and other editors use different API names for the same contract.
This chapter assumes you can read TypeScript, know how a VS Code extension is laid out (package.json plus an activate function), and have read the earlier chapters on context assembly, debouncing and post-processing. Here you wire those ideas into a real extension.
The provider contract
VS Code exposes inline completions through vscode.languages.registerInlineCompletionItemProvider. You pass it two things:
- A document selector, which says which files the provider serves.
{ pattern: '**' }matches every file. - An object with one method,
provideInlineCompletionItems(document, position, context, token).
The editor supplies four arguments:
| Argument | What it gives you |
|---|---|
| `document` | The full text of the file, with helpers such as `getText`, `lineAt` and `positionAt`. |
| `position` | The cursor location as a line and character. |
| `context` | Why the call happened (`triggerKind`) and whether the suggest widget is open (`selectedCompletionInfo`). |
| `token` | A cancellation token that the editor cancels when the request is stale. |
You return an array of InlineCompletionItem objects, an InlineCompletionList, or nothing. An empty array means "no suggestion", and the editor shows nothing.
Each item holds the text to insert and the range it replaces. For a normal completion, use an empty range at the cursor. Then the text is purely inserted and nothing existing is overwritten. Ranges that cover existing text are possible, but the editor requires the text in that range to match the start of your suggestion before it shows ghost text, so they are easy to get wrong.
The request lifecycle
The editor calls your provider on typing and when the user asks explicitly. Fast typists cause many calls, and the editor cancels the earlier ones as new ones arrive. Your job is to do as little work as possible for calls that will be cancelled.
A minimal provider
The following example is the core of a provider. It does four things:
- It waits briefly.
- It checks cancellation.
- It builds the prefix and suffix.
- It returns one item.
import * as vscode from 'vscode';
declare function fetchCompletion(
prefix: string,
suffix: string,
signal: AbortSignal
): Promise<string>;
export function activate(context: vscode.ExtensionContext) {
const provider: vscode.InlineCompletionItemProvider = {
async provideInlineCompletionItems(document, position, _ctx, token) {
// Wait briefly so fast typing does not trigger a request per keystroke.
await new Promise(resolve => setTimeout(resolve, 150));
if (token.isCancellationRequested) {
return [];
}
const controller = new AbortController();
token.onCancellationRequested(() => controller.abort());
const start = new vscode.Position(0, 0);
const end = document.positionAt(document.getText().length);
const prefix = document.getText(new vscode.Range(start, position));
const suffix = document.getText(new vscode.Range(position, end));
const text = await fetchCompletion(prefix, suffix, controller.signal);
if (!text) {
return [];
}
return [new vscode.InlineCompletionItem(text, new vscode.Range(position, position))];
},
};
context.subscriptions.push(
vscode.languages.registerInlineCompletionItemProvider({ pattern: '**' }, provider)
);
}Four details matter here.
- The delay is the debounce. Because the editor cancels superseded calls, a plain
setTimeoutfollowed by a token check is enough. Calls that were cancelled during the wait return before they cost any network traffic. - The abort signal connects two cancellation systems. VS Code uses a
CancellationToken. The webfetchAPI uses anAbortSignal. Bridging them stops the HTTP request itself, which frees your backend to stop generating tokens. - The prefix and suffix come from the same position. They split the document at the cursor. A fill-in-the-middle prompt, covered earlier, places them around the missing middle.
- The subscription is registered on
context.subscriptions. VS Code disposes of it when the extension deactivates.
Declaring the extension
The extension must activate before the user types. A minimal package.json that does this:
{
"name": "tiny-complete",
"displayName": "Tiny Complete",
"version": "0.0.1",
"engines": { "vscode": "^1.85.0" },
"main": "./out/extension.js",
"activationEvents": ["onStartupFinished"]
}onStartupFinished activates after the editor has loaded, so your extension does not slow startup. Compile the TypeScript to out/ and press F5 in VS Code to launch an Extension Development Host for testing.
Calling a backend
The fetchCompletion function was a placeholder. A working version, assuming a local server at an address you control, looks like this:
export async function fetchCompletion(
prefix: string,
suffix: string,
signal: AbortSignal
): Promise<string> {
try {
const response = await fetch('http://localhost:8080/complete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prefix, suffix, max_tokens: 64 }),
signal,
});
if (!response.ok) {
return '';
}
const data = (await response.json()) as { completion?: string };
return data.completion ?? '';
} catch {
// Aborted requests and network errors both mean "no suggestion".
return '';
}
}The global fetch exists in the Node runtime of current VS Code versions. Your TypeScript project needs type definitions for it, which come with @types/node 18 or later. The URL and response shape are invented for this example. Match them to your own server.
The function swallows errors on purpose. A completion feature that throws on every dropped connection fills the extension log and can show error popups. Returning an empty string degrades silently, which is the right behavior for a background feature. Log errors to an output channel if you need to diagnose them.
Limiting the context window
The minimal provider sends the whole file on every request. That is fine for a 50-line script and wasteful for a 20,000-line file. Take a window around the cursor instead. The next version also reuses the post-processing idea from the earlier chapter, trimming text the editor already has after the cursor.
const MAX_PREFIX_LINES = 200;
const MAX_SUFFIX_LINES = 50;
function trimOverlap(completion: string, suffix: string): string {
for (let n = Math.min(completion.length, suffix.length); n > 0; n--) {
if (completion.endsWith(suffix.slice(0, n))) {
return completion.slice(0, completion.length - n);
}
}
return completion;
}
function windowAround(document: vscode.TextDocument, position: vscode.Position) {
const startLine = Math.max(0, position.line - MAX_PREFIX_LINES);
const endLine = Math.min(document.lineCount - 1, position.line + MAX_SUFFIX_LINES);
const start = new vscode.Position(startLine, 0);
const end = document.lineAt(endLine).range.end;
return {
prefix: document.getText(new vscode.Range(start, position)),
suffix: document.getText(new vscode.Range(position, end)),
};
}In the provider, replace the prefix and suffix lines with const { prefix, suffix } = windowAround(document, position);. Then pass the model output through trimOverlap(text, suffix) before building the item. If the trimmed result is empty, return [].
Line limits are a simple heuristic. Real assistants budget by tokens and often add snippets from related files, but a line window is a reasonable first version.
Using the context argument
The unused _ctx parameter carries two useful fields.
triggerKindisInlineCompletionTriggerKind.Automaticwhen the editor asked because the user typed, andInlineCompletionTriggerKind.Invokewhen the user pressed a shortcut to ask explicitly. A common policy is to apply the debounce and extra filters only to automatic calls, and to answer explicit requests immediately.selectedCompletionInfois set when the normal suggestion dropdown is open with an item highlighted. It holds the range and text of that item. Ghost text must be consistent with the highlighted item, so simple providers return nothing while it is set.
A guard for both:
async provideInlineCompletionItems(document, position, ctx, token) {
if (ctx.selectedCompletionInfo) {
return [];
}
if (ctx.triggerKind === vscode.InlineCompletionTriggerKind.Automatic) {
await new Promise(resolve => setTimeout(resolve, 150));
if (token.isCancellationRequested) {
return [];
}
}
// build the request and return items as before
return [];
}Edge cases and common errors
- Forgetting the check after the network call. The token can be cancelled while the request is in flight. If your backend ignores the abort signal and still answers, check
token.isCancellationRequestedagain before returning. - Stale results. If the user types a character that matches the start of your suggestion, VS Code can keep showing the suggestion. If they type something else, it asks again. Do not cache suggestions by position alone.
- Multi-line suggestions at mid-line cursors. If the cursor is in the middle of a line, a multi-line completion can look wrong, because the suffix of that line moves down. Many providers truncate to one line when text follows the cursor on the same line.
- Whitespace-only output. Models sometimes return only a newline or spaces. Treat it as empty, or the user sees a flickering blank suggestion.
- Fixed documents.
document.getText()on a very large file copies the whole file on each call. The windowed approach avoids this. - Provider throws. An unhandled exception loses the suggestion and logs noise. Wrap the body in
try/catchand return[].
Exercise
Your provider waits 150 ms, then calls the backend. A user types three characters in 100 ms intervals, then stops. How many backend requests should be sent, and why? What happens to the first two provider calls?
Show answer
One request. Each keystroke starts a provider call, and the editor cancels the previous call's token when the next one starts. The first two calls wake up from their 150 ms wait, see token.isCancellationRequested is true, and return [] without contacting the backend. Only the third call, which has no newer keystroke after it, still has a live token after the delay and sends the request.
Exercise
A completion returns foo(a, b) and the editor has already auto-inserted a closing ) after the cursor, so the suffix starts with ). What does trimOverlap return, and why does it matter?
Show answer
It returns foo(a, b. The function finds the longest end of the completion that equals the start of the suffix, here ), and removes it. Without trimming, accepting the suggestion would leave two closing brackets in the file.