gantonioid
gantonioid

Reputation: 457

Event VSCode API CodeAction accepted

Is there a way to trigger some code whenever a CodeAction (QuickFix - lightbulb) is applied?

Inside my CustomActionProvider that implements vscode.CodeActionProvider

public provideCodeActions(document: vscode.TextDocument, range: vscode.Range): vscode.CodeAction[] | undefined {
    let ifPowershell = this.isAtIfPS(document, range);
    if (ifPowershell[0] === "true") {
        //Tenemos que calcular el Range, para hacer el replace
        let line = document.lineAt(range.start.line);
        let startIndex = line.firstNonWhitespaceCharacterIndex;
        let range2 = new vscode.Range(new vscode.Position(range.start.line, startIndex), line.range.end);
        //El texto que va a remplazar al código existente
        let fix = `if (${ifPowershell[1]} ${ifPowershell[2]} ${ifPowershell[3]})`;
        return [this.createFix(document, range2, fix)];
    }

    //Si llegamos aquí es que no hay 
    return;
}

private createFix(document: vscode.TextDocument, range: vscode.Range, replace: string): vscode.CodeAction {
    const fix = new vscode.CodeAction(`Convert to ${replace}`, vscode.CodeActionKind.QuickFix);
    fix.edit = new vscode.WorkspaceEdit();
    fix.edit.replace(document.uri, new vscode.Range(range.start, range.end), replace);
    return fix;
}

I can already suggest this

enter image description here

Both if (var -eq 0) and if (var == 0) will work, but they are different in performance. So, the recommendation is to use the == operator instead of -eq

Now... I want to count how many users accepted this quickfix, and I already have an API to log that in a database.

The question is: how to code an event, callback or some function that will be triggered whenever the quickfix is 'accepted' by the user?

Upvotes: 1

Views: 366

Answers (1)

Matt Bierner
Matt Bierner

Reputation: 65223

You can use CodeAction.command for this.

First register an internal command:

vscode.commands.registerCommand('_myExt.didApplyFix', () => { 
    // handle fix applied
})

Then use this command on the code action you return:

const action = new vscode.CodeAction('action title');
action.command = { command: '_myExt.didApplyFix', title: 'action title' }

The command will be invoked whenever the fix is applied

Upvotes: 1

Related Questions