When you press Alt+Shift+F in VS Code, or when editor.formatOnSave fires, VS Code looks for a registered DocumentFormattingEditProvider for the active document's language. If it finds one (or more — there can be multiple and VS Code lets you choose), it calls provideDocumentFormattingEdits() and applies the returned edits to the document.
The registration
const provider = vscode.languages.registerDocumentFormattingEditProvider('*', {
provideDocumentFormattingEdits(
document: vscode.TextDocument
): vscode.ProviderResult<vscode.TextEdit[]> {
const fullText = document.getText();
if (!fullText || fullText.trim() === '') {
return [];
}
const indentSize = vscode.workspace.getConfiguration(
'mkhCodeFormatter', document.uri
).get<number>('indentationSize', 2);
const formatted = formatText(fullText, document.languageId, indentSize);
const entireRange = new vscode.Range(
document.positionAt(0),
document.positionAt(fullText.length)
);
return [vscode.TextEdit.replace(entireRange, formatted)];
}
});
context.subscriptions.push(provider);The '*' language ID means "register for all languages." This makes the extension appear in VS Code's "Format Document With..." picker for any file, but it only becomes the automatic formatter when explicitly set as editor.defaultFormatter for a language.
The TextEdit return
VS Code's formatting API expects an array of TextEdit objects — each one describing a range to replace and what to replace it with. The simplest approach (and the one mkhCodeFormatter uses) is a single TextEdit that replaces the entire document content with the formatted output. VS Code applies this atomically, preserving undo history as a single operation.
The dedicated command
Alongside the formatting provider, the extension registers a command (mkh-codeformatter.formatCode) bound to Ctrl+Alt+F. This command reads the active editor's document, runs the same formatText() function, and applies the result via editor.edit(). This gives users a dedicated hotkey that works regardless of which formatter is set as default for the language.
Configuration reading
The vscode.workspace.getConfiguration('mkhCodeFormatter', document.uri) call reads the mkhCodeFormatter.indentationSize setting with the document's URI as scope — this means workspace-level settings correctly override user-level settings, following VS Code's standard configuration resolution order.
---
