Reputation: 328
I have an extension in which I query the source path of the current active tab file.
For textual files, the following works great:
const activeEditor: TextEditor = window.activeTextEditor;
if (activeEditor && activeEditor.document && activeEditor.document.fileName) {
return activeEditor.document.fileName;
}
Problem is, this doesn't work when the active file in the text editor is non-textual, for example an image file such as a .jpg
.
For these types of files, window.activeTextEditor
is undefined
. Moreover, when I try running the following code:
const uri = Uri.file(<path_to_binary_file>);
workspace.openTextDocument(uri);
I receive the following error: "cannot open <path_to_file>. Detail: File seems to be binary and cannot be opened as text"
, and I don't see any similar API to openTextDocument
that deals with non-textual files.
Is there any straightforward way of obtaining this data without using commands.executeCommand('workbench.action.files.copyPathOfActiveFile')
and various clipboard manipulations?
Upvotes: 4
Views: 1631
Reputation: 570
Here is a workaround:
const getSourcePathForNonTextFile = async (): Promise<string> => {
// Since there is no API to get details of non-textual files, the following workaround is performed:
// 1. Saving the original clipboard data to a local variable.
const originalClipboardData = await vscode.env.clipboard.readText();
// 2. Populating the clipboard with an empty string
await vscode.env.clipboard.writeText("");
// 3. Calling the copyPathOfActiveFile that populates the clipboard with the source path of the active file.
// If there is no active file - the clipboard will not be populated and it will stay with the empty string.
await vscode.commands.executeCommand("workbench.action.files.copyPathOfActiveFile");
// 4. Get the clipboard data after the API call
const postAPICallClipboardData = await vscode.env.clipboard.readText();
// 5. Return the saved original clipboard data to the clipboard so this method
// will not interfere with the clipboard's content.
await vscode.env.clipboard.writeText(originalClipboardData);
// 6. Return the clipboard data from the API call (which could be an empty string if it failed).
return postAPICallClipboardData;
};
Upvotes: 0
Reputation: 328
It seems that this is a known open issue in VS code. The following Github issue discusses it.
Upvotes: 1