Copy/paste to and from the system clipboard in Vim

May 17, 2010 by Merlin

Users accustomed to CTRL+C/V keyboard shortcuts may find themselves reaching for the mouse when using gVim or Vim in a terminal because aforementioned commands do not work by default. So, how to do it?

Short answer would be to select a text in a Visual or Select mode, type "+y and you have the selected text in a system clipboard. If you need to paste, position your cursor where you want it and type "+p. "+ is just a register, so you can use different yank/put commands with it like "+6yy or "+gP.

Long answer would be … well, long. Vim uses registers "+ and "* to communicate with other applications. How it does that depends on the operating system Vim runs on.

Windows

Using "+ and "* registers will bring the same results. They both map to the Windows system clipboard that is persistent even after Vim closes. You can use one trick that works great in Windows Vim. When the “unnamed” string is included in the ‘clipboard’ option (:set clipboard=unnamed), the unnamed register is the same as the "* register.  Thus you can yank to and paste the selection without prepending "+ or "* to commands. Type 3dd, go to your favorite spreadsheet and paste 3 lines you’ve just deleted in Vim with CTRL+V. Works like a charm.

Note: be careful when using unnamed clipboard if you are known to hold data in a clipboard for some time because you will overwrite it very easily while doing even minor editing in Vim.

Linux

(tested on Ubuntu)

Typing :help x11-selection says:

If using X11, in either the GUI or an xterm with an X11-aware Vim, then Vim provides varied access to the X11 selection and clipboard.  These are accessed by using the two selection registers "+ and "*.

X11 provides two basic types of global store, selections and cut-buffers, which differ in one important aspect: selections are “owned” by an application, and disappear when that application (e.g., Vim) exits, thus losing the data, whereas cut-buffers, are stored within the X-server itself and remain until written over or the X-server exits (e.g., upon logging out).

In short – you close Vim, you can’t paste data from it.

In this environment Vim differentiates "+ and "* registers. The former is (automatically) filled when you make or update any selection. This works across the system and if you select some text in your inbox, the content in "* is overwritten with new selection. When you press the middle mouse button, everything from the "* is pasted in a place where a mouse cursor is pointing, be it from Vim or your inbox selection. The "+register works more Windows-like. When you yank to it, it persists while Vim is opened and you can use CTRL+V to paste its contents to other applications regardless of other selections.

That’s it. Happy yanking Vim users (this sounded weird).