Home > Enterprise >  How to remove the diagnostic content on hover in my VS Code extension?
How to remove the diagnostic content on hover in my VS Code extension?

Time:01-12

In my VS Code extension, I have registered a command to remove a diagnostic:

extension.ts

context.subscriptions.push(
    vscode.commands.registerCommand(
        DELETE_DIAGNOSTIC_COMMAND, 
        () => removeDiagnostic()
    )
);

This is what the removeDiagnostic function looks like:

utils.ts

export function removeDiagnostic(): void {
    const editor = window.activeTextEditor;
    if(editor){
        const diagnosticStart = editor.selection.start;
        const diagnosticEnd = editor.selection.end;
        const diagnosticRange = new Range(diagnosticStart, diagnosticEnd);
        editor.edit(editBuilder => {
            editBuilder.replace(diagnosticRange, "");
        });
}

The DELETE_DIAGNOSTIC_COMMAND is provided here as a code action:

MyCodeActionProvider.ts

const DELETE_DIAGNOSTIC_COMMAND = 'delete-diagnostic.command';

export class MyCodeActionProvider implements vscode.CodeActionProvider {

    public static readonly providedCodeActionKinds = [
        vscode.CodeActionKind.QuickFix
    ];

    provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.CodeAction[] {
        return context.diagnostics
            .filter(diagnostic => diagnostic.code === 'myDiagnosticCode')
            .map(diagnostic => this.createCommandCodeAction(diagnostic));
    }

    private createCommandCodeAction(diagnostic: vscode.Diagnostic): vscode.CodeAction {
        const action = new vscode.CodeAction('Remove deprecated intrinsic', vscode.CodeActionKind.QuickFix);
        action.command = { command: DELETE_DIAGNOSTIC_COMMAND, title: 'Remove deprecated intrinsic', tooltip: 'This will remove the deprecated intrinsic from the editor.' };
        action.diagnostics = [diagnostic];
        action.isPreferred = true;
        return action;
    }
}

And, the code actions provider is registered here:

extension.ts

context.subscriptions.push(
    vscode.languages.registerCodeActionsProvider('myFileExtension', new MyCodeActionProvider(), {
        providedCodeActionKinds: MyCodeActionProvider.providedCodeActionKinds
    })
);

In the removeDiagnostic function, I want to get the diagnostic's range when I hover on the diagnostic, in order to run the quick-fix command to remove it.

To be more clear, when I run the command from the Problems tab, I am able to remove the selected range, but not when I hover on the diagnostic:

code-action-command

How can I remove the diagnostic from the editor when I run the command after I hover on it?

CodePudding user response:

Pass the diagnostic from the code action to your DELETE_DIAGNOSTIC_COMMAND command in the args property and use the range property of the diagnostic in the command

  •  Tags:  
  • Related