Raw Power of Vim: Integrating System Clipboard

If I were asked to pick two applications to keep on a computer, I would probably say Vim and browser. The former for coding and the latter for looking up documentation. As such, I often have copy and pasting between the two.Today we will learn how to set up Vim to copy and paste to system clipboard, both on local machine and on remote server with X11 forwarding.

Vim’s Clipboard Support

First, we need to check if the Vim your computer ships with support clipboard. In terminal, type

vim --version | grep clipboard # grep will search for sentences containing clipboard

If you see -clipboard and -xterm_clipboard, it means vim doesn’t support clipboard. On Ubuntu or Debian distro, type sudo apt-get install vim-gtk to get clipboard support.

Local Machine

All that remain is simply getting used to using the clipboard registers. If you are not familiar with how they works, check out my previous post.

Clipboard Registers

Now if you type :reg in command mode, you will see that you have two extra registers: "* and "+. These are the clipboard registers your os uses. On Windows or Mac OS, these two are the same clipboard. On Linux, "+ is the clipboard that Ctrl-C, Ctrl-X, and Ctrl-V uses, while "* is the current mouse selection. (Did you know? On Linux you can middle click to paste your mouse selection.)

Now to copy to system clipboard: "+y
To paste from system clipboard: "+p

Default Copy and Paste to Clipboard Register

Usually you don’t really care about all these register except the clipboard. You can add the following to .vimrc to set your clipboard register("+) the same as your unnamed register("").

:set clipboard=unnamedplus

Now yy and p will also use the system clipboard. Not that hard, was it?

Remote Server

Copying from remote server to local machine’s system clipboard is not that much harder. All we need to do is enabling server’s vim clipboard register(same as local machine) and setting up X11 forwarding.

X11 Forwarding

X11 is a protocol of transferring GUI information. In X11 forwarding, we ask the server to forward GUI information to our local machine, including the clipboard.

The specifics differ from servers to servers, but usually you want to locate the /etc/ssh/sshd_config file, and have the following line:

X11Forwarding yes

After that, ssh with the -Y option: ssh -Y user@server
Viola! You can now copy and paste to system clipboard.

2 Replies to “Raw Power of Vim: Integrating System Clipboard”

Leave a Reply

Your email address will not be published. Required fields are marked *