Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vscode extension, setting window.activeTextEditor

How can I use the vscode extension api to set the activeTextEditor?

The reason I need this is because my extension depends on an external call to extension B, and extension B does not take an argument for editor. It just looks at vscode.window.activeTextEditor.

My extension is a webview which calls Extension B when something is clicked on the webview. At that moment in time, the 'active tab' is the webview, which is not activeTextEditor that I want.

I want to do something like

vscode.window.activeTextEditor = editor

at the start of my click handler, but this doesn't work because activeTextEditor is not a setter.

I tried making a fake edit on the editor in question:

function changeFocus(editor: vscode.TextEditor) {
  return editor.edit((editBuilder) => {
    const pos = new vscode.Position(0, 0);
    const nxt = new vscode.Position(0, 1);
    editBuilder.insert(pos, "\\");
    editBuilder.delete(new vscode.Range(pos, nxt));
  });
}

but this does not change vscode.window.activeTextEditor variable (it is still undefined).

like image 910
Antti S. Avatar asked May 09 '26 00:05

Antti S.


1 Answers

If I understand correctly, this opens and focuses another file:

const currentWorkSpace = await vscode.workspace.getWorkspaceFolder(vscode.window.activeTextEditor.document.uri);

vscode.window.showTextDocument(vscode.Uri.joinPath(currentWorkSpace.uri, 'search/oldSearch.js'), { preview: false });

It is focussed and writable at its previously saved cursor position.

showTextDocument() has two other forms, one of which can take a TextDocument as the file to be opened, rather than a Uri.

There is also openTextDocument() which can create a new untitled file if you wish.

If the file is already open, this code will still serve to focus it and thus you have your activeTextEditor.

like image 148
Mark Avatar answered May 11 '26 14:05

Mark



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!