Home > Blockchain >  VSCode Extension API - listen for built-in context menu events
VSCode Extension API - listen for built-in context menu events

Time:12-15

I am building my first VSCode Extension and struggling a little bit.

Is it possible to listen to context menu events, like copy for example?

For example: When user clicked on "Copy" in the context menu (screenshot of context menu) I want to get the copied text.

There is an option to add commands to the context menu. But I don't want that, I want to listen to the existing built-in copy command.

I know, I can listen to the keybinding, but that doesn´t trigger the context menu event.

CodePudding user response:

Here is a better version of my previous answer - it just gets the clipboard text in an easier method:

let typeDisposable = vscode.commands.registerCommand('editor.action.clipboardCopyAction', async (arg) => myCopy(typeDisposable) );

async function myCopy(typeDisposable)  {

    typeDisposable.dispose();      // must dispose to avoid endless loops

    // run the built-in copy command
    await vscode.commands.executeCommand('editor.action.clipboardCopyAction');

    // get the copied text
    const clipboardText = await vscode.env.clipboard.readText();
    // use your clipboard text here
    console.log(clipboardText);

    // re-register to continue intercepting copy commands
    typeDisposable = vscode.commands.registerCommand('editor.action.clipboardCopyAction', async (arg) => myCopy(typeDisposable) );
    context.subscriptions.push(typeDisposable);
}

context.subscriptions.push(typeDisposable);

  • [Previous version of answer]

This seems to work - but should be thoroughly tested (it is sort of a thought experiment at this point):

let typeDisposable = vscode.commands.registerCommand('editor.action.clipboardCopyAction', async (arg) => myCopy(typeDisposable) );

async function myCopy(typeDisposable)  {

    typeDisposable.dispose();

    // get the selectedText from the editor here
    const selectedRange = new vscode.Range(vscode.window.activeTextEditor.selection.start, vscode.window.activeTextEditor.selection.end);
    const copiedText = vscode.window.activeTextEditor.document.getText(selectedRange);
    // use your copiedText here

    await vscode.commands.executeCommand('editor.action.clipboardCopyAction');
    typeDisposable = vscode.commands.registerCommand('editor.action.clipboardCopyAction', async (arg) => myCopy(typeDisposable) );
    context.subscriptions.push(typeDisposable);
}

context.subscriptions.push(typeDisposable);

You would have to modify this for multiple selections which should be pretty easy.

This will intercept ALL calls to copy, including Ctrl C. Maybe you are able to limit registering the command to a more limited set of circumstances?

  • Related