在VS代码扩展中,如何在用户剪切/复制/粘贴时收到通知?

时间:2017-06-16 22:39:46

标签: visual-studio-code vscode-extensions

对于我的扩展,我需要知道何时发生剪切/复制/粘贴,并且能够获得与这些操作相关联的文本。如果我知道何时发生,我可能会从编辑器中获取文本。

我找不到这些操作的监听器。我想我可以查找ctrl-x,ctrl-c和ctrl-v键盘输入,但有些用户可能会使用编辑菜单而不使用键盘。

有没有办法在键盘或编辑菜单发生这些操作时收到通知?

2 个答案:

答案 0 :(得分:1)

没有api可以直接访问剪贴板,但有些扩展会覆盖默认的复制和粘贴快捷方式来自定义复制粘贴行为。以下是两个例子:

正如您所注意到的那样,使用上下文菜单进行复制时,该方法无效。为了支持这一点,您可以尝试拦截editor.action.clipboardCopyAction命令。有关此示例,请参阅Vim扩展如何拦截type命令:https://github.com/VSCodeVim/Vim/blob/aa8d9549ac0d31b393a9346788f9a9a93187c222/extension.ts#L208

答案 1 :(得分:0)

原来的提问者......

我提出了一个解决方案,涉及在编辑器中覆盖默认的剪切/复制/粘贴操作。这是' copy'的代码。在extension.js中(我使用的是js而不是ts):

//override the editor.action.clipboardCopyAction with our own
var clipboardCopyDisposable = vscode.commands.registerTextEditorCommand('editor.action.clipboardCopyAction', overriddenClipboardCopyAction); 

context.subscriptions.push(clipboardCopyDisposable);

/*
 * Function that overrides the default copy behavior. We get the selection and use it, dispose of this registered
 * command (returning to the default editor.action.clipboardCopyAction), invoke the default one, and then re-register it after the default completes
 */
function overriddenClipboardCopyAction(textEditor, edit, params) {

    //debug
    console.log("---COPY TEST---");

    //use the selected text that is being copied here
    getCurrentSelectionEvents(); //not shown for brevity

    //dispose of the overridden editor.action.clipboardCopyAction- back to default copy behavior
    clipboardCopyDisposable.dispose();

    //execute the default editor.action.clipboardCopyAction to copy
    vscode.commands.executeCommand("editor.action.clipboardCopyAction").then(function(){

        console.log("After Copy");

        //add the overridden editor.action.clipboardCopyAction back
        clipboardCopyDisposable = vscode.commands.registerTextEditorCommand('editor.action.clipboardCopyAction', overriddenClipboardCopyAction);

        context.subscriptions.push(clipboardCopyDisposable);
    }); 
}

这绝对不是感觉最好的解决方案......但它似乎确实有效。有什么意见/建议吗?是否存在重复注册和取消注册的问题?