Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close specific open tabs using VSCode extension API

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:

Error message

Is there a way that I can close all open tabs based on the filename before I delete the files?

like image 489
buenon Avatar asked Nov 07 '22 06:11

buenon


1 Answers

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);
}
like image 136
CascadiaJS Avatar answered Nov 13 '22 06:11

CascadiaJS