I'm writing an extension which creates temporary scratch files. I want to allow the user to remove all scratch files.
My issue occurs when I have scratch files open in the editor. If I simply delete the files I get error messages that the files do not exist:
Is there a way that I can close all open tabs based on the filename before I delete the files?
To avoid this error close the open text editors before you delete the associated file.
vscode.workspace.textDocuments
contains an array of the open text documents. Before deleting the document, filter the vscode.workspace.textDocuments
array to only include the text documents for the files you want to delete, then loop over the filtered array (loop don't use forEach because closing and deleting text documents is asynchronous) and bring each text editor into focus then close it. Then run your delete code. Like this:
const filteredTextDocuments = vscode.workspace.textDocuments.filter(td => td.fileName === 'scratchFileName')
for (const td of filteredTextDocuments) {
await vscode.window.showTextDocument(td, { preview: true, preserveFocus: false });
await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
await vscode.workspace.fs.delete(td.uri);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With