简体   繁体   English

使用 VSCode 扩展 API 关闭特定打开的选项卡

[英]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:如果我只是删除文件,我会收到文件不存在的错误消息:

错误信息

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. vscode.workspace.textDocuments包含一组打开的文本文档。 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.在删除文档之前,过滤vscode.workspace.textDocuments数组以仅包含要删除的文件的文本文档,然后遍历过滤后的数组(循环不要使用 forEach,因为关闭和删除文本文档是异步的)和将每个文本编辑器置于焦点然后关闭它。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM