Sunday, May 20, 2012

vim: using the system clipboard

It annoyed me that I couldn't yank (copy) something in vim using y and then paste it in something else with ctrl-v, or vice versa. I found that the following line (linux, x11, vim 7.3), makes it just work:

:set clipboard=unnamedplus

What's going on here?
vim has "registers." Each register is like its own clipboard. You can choose your register with ". So for example:
means "using the a register ("a), copy/yank the current line (yy)". But most of the registers only live within vim. Vim has two special registers though: * and +. On Windows and Mac, they are both the system clipboard. On X11 they are different and only the + is the system clipboard. So in vim on either system, you should be able to type:
to copy the current line into the system clipboard, and then ctrl-v in a windowed application to paste it. Then the "set clipboard=unnamedplus" line just makes the + register the default one.

More info from vim tips here and here.

Side note: I think that by saying "system clipboard" I am being a little vague because there are actually three system clipboards in X11, but the ctrl-c ctrl-v one is the one I always want. I think this is called, amusingly, the CLIPBOARD clipboard. More here.

Another side note: on my older Macbook (OS X 10.6.8 Snow Leopard), I couldn't easily get Vim 7.3.74+ (where clipboard=unnamedplus is introduced). The MacVim version available is 7.3.53. However, as mentioned above, * and + are both the system clipboard on a Mac, so set clipboard=unnamed works. (be careful if using tmux.) You can check if unnamedplus is available, so my .vimrc now looks like:
if has('unnamedplus')

  set clipboard=unnamedplus
  set clipboard=unnamed

No comments:

Post a Comment