Monday, April 11, 2011

Making Vim copy all yanked text to the system clipboard

In addition to the usual cut and paste operations found in most other editors, Vim has a 'yank' command that can be followed by a motion operator.

So you can type yw to copy a word to the clipboard, or y3w to copy three words, or yip to copy the current paragraph to the clipboard, and so on.

Which is useful. But by default the text copied by the yank command is only accessible from within that same instance of Vim.

So if you've opened another instance of Vim in a new window[1] and you want to paste the text into that, or you want to paste it into another program, you can't.

An IMO problematic solution is to set 'unnamed' in the 'clipboard' option in your .vimrc / _vimrc, like so

set clipboard+=unnamed

this works but it has a downside - it also means all deleted text gets sent to the system clipboard.

Most of the time I delete text because I just want to get rid of it. When I tried setting this option I kept overwriting the clipboard contents (that I did want) with the deleted text that I didn't want.

And if you do actually want to delete text _and_ copy it to the clipboard you can use a cut command - i.e. C-x. So set clipboard+=unnamed doesn't seem like a good idea.

Here's a better solution, that just ensures yanked text is copied to the system clipboard. Just add the following line to your .vimrc / _vimrc:

nnoremap y "+y

The "+ tells Vim to yank into the + register, which is the system register.

[1] I know many people like to work within one Vim instance and use splits/buffers and tabs to arrange their files, and may want to suggest this as an alternative, but I find it very useful to work with multiple Vim instances. It's a long story, but I like to be able to spatially arrange the (OS)windows in a certain way that reflects the relationship between the files in them, and you can't achieve what I want with a single Vim instance.