Reputation: 885
We tried to execute VSCode's Organize imports
command like this: vscode.commands.executeCommand('editor.action.organizeImports')
and it executes successfully: in a test file we see that imports have been ordered and the file is not saved.
We would like to write an extension that further formats/orders/sorts the imports, so we wanted to write our code in a callback of executeCommand
, like this:
export function activate(context: vscode.ExtensionContext) {
const sortDisposable = vscode.commands.registerTextEditorCommand(SORT_EXTENSION_ID, (editor: vscode.TextEditor) => {
// execute VS Code's Organize imports command
return vscode.commands
.executeCommand('editor.action.organizeImports')
.then(_ => {
const content: string = editor.document.getText();
console.log(`contet`, content)
}, _ => console.log(`failure`));
});
context.subscriptions.push(sortDisposable);
}
However, editor.document.getText()
actually returns the state of the document before the VS Code's Organize imports
has organized imports.
In other words, the callback that we provided is not executed after VSCode's Organize imports
.
We also tried this suggestion, but it doesn't work.
Is there a way to get a true callback from VSCode, after it has executed a command? According to this sample (from the VSCode's team itself) it is possible to do, but for some reason it's not working for us. Is it because we are calling a VSCode's internal method? Does someone have a suggestion what can we do here?
Upvotes: 2
Views: 1784
Reputation: 275
editor.action.organizeImports
isn't listed as an option within executeCommand docs here, so that could be the source of your problems. I'm not sure how to refactor the vscode.commands.registerTextEditorCommand
parameters, but you could try converting your function to an async/await one:
export async function activate(context: vscode.ExtensionContext) {
...
await vscode.commands.executeCommand('editor.action.organizeImports');
const content: string = editor.document.getText();
...
}
This works successfully when I used vscode.commands.executeCommand(vscode.openFolder, args)
. You could then experiment with const var = await vscode.commands.executeCommand('editor.action.organizeImports')
to see if var
is populated with anything useful for you to process.
Upvotes: 1