Sub topic 7
Writing a Completion Provider in an Editor Extension
This chapter assumes you can read TypeScript, have built or at least run a VS Code extension, and know the earlier chapters' ideas: prefix and suffix context, debouncing, and cancellation. Here you will see how those ideas map onto the editor's extension API.
What the editor gives you
VS Code lets an extension register an inline completion provider. The editor calls your provider whenever it thinks a suggestion might be useful. You do not draw ghost text yourself. You return a list of InlineCompletionItem objects, and the editor renders the first one as grey text at the cursor. It also handles Tab to accept, Escape to dismiss, and cycling through alternatives.
The provider receives four inputs:
| Parameter | What it holds |
|---|---|
| `document` | The full text of the file and helpers to convert offsets to positions |
| `position` | The cursor location |
| `context` | Why the request happened (typing or an explicit trigger) and any suggestion already shown |
| `token` | A cancellation token that fires when the request is stale |
The request lifecycle
A complete provider
This is the provider from the topic's code example. Read it in four steps.
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)
);
}- Debounce. The 150 ms sleep is a simple debounce. Each keystroke starts a new call, and the editor cancels the older one. A call that was cancelled during the sleep returns early without touching the network.
- Cancellation. The
AbortControllerlinks the editor's token to the HTTP request. Without it, abandoned requests keep running and waste backend capacity. - Context. The prefix runs from the file start to the cursor. The suffix runs from the cursor to the end of the file. A real provider would trim both to a token budget and add related files, as covered in the context assembly chapter.
- Result. The item's range is empty,
positiontoposition, so the text is inserted at the cursor and replaces nothing.
Registration uses a document selector. { pattern: '**' } matches every file. In practice you would restrict it to languages you support, for example { language: 'python' }.
Plugging in earlier ideas
Before returning text, run the post-processing step from the earlier chapter, such as trim_overlap, so a closing bracket the editor already inserted is not duplicated. Build the model prompt from prefix and suffix with the fill-in-the-middle format your model expects.
Common errors
- Returning stale results. If you skip the cancellation check after
await, a slow response can appear after the user has moved on. Checktoken.isCancellationRequestedafter every long wait. - Ignoring the abort. Passing the signal to
fetchis not enough if your own code swallows theAbortErrorand returns text. Return[]on abort. - Sending whole large files. Reading the entire document on each keystroke is slow for big files. Cap the context length.
- Throwing from the provider. An uncaught exception shows nothing to the user and can disable the feature silently. Catch errors and return
[].
Exercise
The provider sleeps 150 ms, then checks token.isCancellationRequested before calling the model. Why is that check useful, and what would happen without it?
Show answer
If the user typed during the 150 ms, the editor has already cancelled this call. The check returns early, so no request is sent. Without it, the provider would send a model request for outdated context, which wastes backend work and adds load for no visible result.
Exercise
What range would you give an InlineCompletionItem if you wanted its text to replace the rest of the current line, rather than only insert at the cursor?
Show answer
A range from position to the end of the line, for example new vscode.Range(position, document.lineAt(position.line).range.end). The editor then replaces that span with the item's text.