Search code examples
bashvimwindows-subsystem-for-linux

How to "copy to clipboard" in vim of Bash on Windows?


I used to use "+y to copy text to system's clipboard, but it doesn't work in vim of Bash on Windows.


Solution

  • Since neither "*y nor "+y (...) work, an alternative is the following:

    Add this to your .vimrc and create a file called ~/.vimbuffer

    " copy (write) highlighted text to .vimbuffer
    vmap <C-c> y:new ~/.vimbuffer<CR>VGp:x<CR> \| :!cat ~/.vimbuffer \| clip.exe <CR><CR>
    " paste from buffer
    map <C-v> :r ~/.vimbuffer<CR>
    

    Higlight any text using visual or visual-block and press ctrl-c. Paste copied text outside your terminal using the usual method or paste copied text to any vim pane using ctrl-v in normal or visual mode.

    Ctrl-c yanks the selected text, overwrites ~/.vimbuffer with the selected text, runs a UNIX command to pipe out the data from ~/.vimbuffer to clip.exe.

    Any further improvement (e.g.: making command silent) is much appreciated!

    Edit: command can now copy strings with any length, not just whole lines. Old command:

    vmap <C-c> :w! ~/.vimbuffer \| !cat ~/.vimbuffer \| clip.exe <CR><CR>

    Edit2: @Tropilio below has a much cleaner approach down in the comments using system events. I've been using that for a year now.