如何在VS Code中关闭TextDocument?

17
我正在编写 vscode 扩展。
我使用 vscode.window.showTextDocument 打开了一个 TextDocument,现在想以后再关闭它。但是我找不到关闭文档的 API。最终我发现 这个提交已经移除了 closeTextDocument。现在该怎么办?
2个回答

16

我遇到了同样的问题。我唯一成功的方法是通过workbench.action.closeActiveEditor,正如TextEditor.hide内联文档所建议的那样。

这种方法有些hackish - 基本上是在编辑器中显示文档,然后关闭活动编辑器:

vscode.window.showTextDocument(entry.uri, {preview: true, preserveFocus: false})
    .then(() => {
        return vscode.commands.executeCommand('workbench.action.closeActiveEditor');
    });

showTextDocument() returns a Thenable<TextEditor> so why you need to invoke a command instead of using the value from the promise? i.e. then((textEditor) => textEditor.hide()) - Sebastian
2
@Sebastian 因为 textEditor.hide 已经被弃用。根据 VSCode 文档:
请使用命令 workbench.action.closeActiveEditor 替代。这种方法会出现意外行为,并将在下一个主要更新中删除。
- tjohnson
你能否通过编程阻止或自动回答“是否保存更改?”的问题? - DarkTrick

6
自从VSCode v1.67版开始,您可以使用TabGroups查找和关闭您喜欢的文档。例如(在TypeScript中):
import * as vscode from "vscode";

export async function closeFileIfOpen(file:vscode.Uri) : Promise<void> {
    const tabs: vscode.Tab[] = vscode.window.tabGroups.all.map(tg => tg.tabs).flat();
    const index = tabs.findIndex(tab => tab.input instanceof vscode.TabInputText && tab.input.uri.path === file.path);
    if (index !== -1) {
        await vscode.window.tabGroups.close(tabs[index]);
    }
}

示例用法:

const myFile = vscode.Uri.file('c:\some\random\file.txt');
await closeFileIfOpen(myFile);

参考资料:最初灵感来自于ct_jdr的回答


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接