I’m developing an extension for VSCode to formatting files via the context menu. Unlike other extensions, I want to do this without opening the file in the text editor.
I tried the following code:
async function formatDocument(uri: vscode.Uri) {
if (uri && uri.fsPath) {
const filePath = uri.fsPath;
try {
let content = await fs.readFile(filePath, 'utf8');
const document = await vscode.workspace.openTextDocument({
content,
language: getLanguageFromPath(filePath)
});
const edits: any[] = await vscode.commands.executeCommand('vscode.executeFormatDocumentProvider', document.uri, getLanguageFromPath(filePath));
if (edits && edits.length > 0) {
const edit = new vscode.WorkspaceEdit();
edits.forEach(e => edit.replace(document.uri, e.range, e.newText));
await vscode.workspace.applyEdit(edit);
const formattedContent = document.getText();
await fs.writeFile(filePath, formattedContent, 'utf8');
vscode.window.showInformationMessage("File formatted successfully!");
}
} catch (error: any) {
vscode.window.showErrorMessage(`Error formatting file: ${error.message}`);
}
}
}
While it does work, it leaves an open file in the editor due to the vscode.workspace.openTextDocument method.
Is there another way to format a file without opening it in the editor?
New contributor
Vinícius Iancovski is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.