【问题标题】:Event VSCode API CodeAction accepted事件 VSCode API CodeAction 接受
【发布时间】:2021-06-15 22:06:13
【问题描述】:

有没有办法在应用 CodeAction(QuickFix - 灯泡)时触发一些代码?

在实现 vscode.CodeActionProvider 的 CustomActionProvider 内部

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;
}

我已经可以建议了

if (var -eq 0)if (var == 0) 都可以,但它们的性能不同。因此,建议使用== 运算符而不是-eq

现在...我想计算有多少用户接受了这个 quickfix,而且我已经有一个 API 可以将它记录到数据库中。

问题是:如何编写一个事件、回调或一些函数,只要用户“接受”快速修复,就会触发这些函数?

【问题讨论】:

  • 一般来说,当有人运行您的扩展程序的 quickfix/灯泡时,您是要询问,还是要为 tslint 本身注入?
  • 事件,当有人运行 quickfix/灯泡时
  • 那么你的具体扩展是什么?
  • 正确,我已经有一个为用户提供快速修复的扩展。这里的问题是当用户应用灯泡建议的更改时,我想运行一些代码。
  • 我已经解决了实际的快速修复。但我也想登录某个用户接受给定建议的数据库。

标签: visual-studio-code vscode-extensions


【解决方案1】:

您可以为此使用CodeAction.command

先注册一个内部命令:

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

然后在您返回的代码操作上使用此命令:

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

每当应用修复时都会调用该命令

【讨论】:

  • 我编辑了答案以添加该命令可以使用参数来传递有关已应用修复的更多详细信息,可能是行号、修复类型、严重级别等。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多