Reputation: 5344
I'm writing vscode extension.
I opened a TextDocument with vscode.window.showTextDocument
, and want to close it later. But I can't find api to close it. Finally I found this commit, it removed closeTextDocument
. What should I do now?
Upvotes: 19
Views: 4493
Reputation: 161
Since VSCode v1.67 you can use TabGroups
to find and close the document of your liking.
E.g. like this (in 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]);
}
}
Example usage:
const myFile = vscode.Uri.file('c:\some\random\file.txt');
await closeFileIfOpen(myFile);
Ref: originally inspired by this answer from ct_jdr.
Upvotes: 9
Reputation: 285
I encountered the same problem. The only way I managed to do it is via workbench.action.closeActiveEditor
, as recommended by the inline documentation for TextEditor.hide
.
It's hackish - basically show the document in the editor, then close the active editor:
vscode.window.showTextDocument(entry.uri, {preview: true, preserveFocus: false})
.then(() => {
return vscode.commands.executeCommand('workbench.action.closeActiveEditor');
});
Upvotes: 17