2017-06-16 94 views
0

對於我的擴展,我需要知道何時發生剪切/複製/粘貼,並能夠獲取與這些操作相關的文本。如果我知道他們發生,我大概可以從編輯器中獲得文本。在VS Code擴展中,如何在用戶剪切/複製/粘貼時通知我?

我找不到這些操作的偵聽器。我想我可以查找ctrl-x,ctrl-c和ctrl-v鍵盤輸入,但有些用戶可能會使用編輯菜單而不使用鍵盤。

當鍵盤或編輯菜單發生這些操作時,有沒有辦法通知?

回答

1

沒有API直接訪問剪貼板,但有些擴展會覆蓋默認的副本並粘貼快捷方式來自定義複製粘貼行爲。這裏有兩個例子:

如你,但是請注意使用上下文菜單複製時的做法是行不通的。爲了支持這一點,你可以嘗試攔截editor.action.clipboardCopyAction命令。在Vim擴展如何攔截type命令一個這樣的例子:在這裏https://github.com/VSCodeVim/Vim/blob/aa8d9549ac0d31b393a9346788f9a9a93187c222/extension.ts#L208

+0

是的,這對我很有用。你知道任何有關overrideCommand()的文檔嗎? 我需要仍然可以執行默認行爲:vscode.commands.executeCommand(「default:editor.action.clipboardPaste Action」); ? –

0

原始提問者...

我想出了包括覆蓋在編輯器中默認的剪切/複製/粘貼操作的解決方案。下面是在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); 
    }); 
} 

這絕對不感覺是最好的解決方案...然而,它確實工作。任何意見/建議?是否有任何重複註冊和註銷會導致的問題?

相關問題