Writing from Vim straight into the X clipboard

I use Vim almost exclusively for my text editing. Every now and again I need to get the contents of the file into the clipboard so I can paste it into something, like a browser window maybe. Highlighting with a mouse is fine for occasional use, but if you’re doing it frequently or if you need to select more than is visible on the screen it’s annoying.

There’s a handy command called xclip that lets you put things directly into the clipboard. For pasting into a browser with Ctrl-V you need to specify the right clipboard (there’s more than one), but something like this:

What I’ve found particularly useful is to write content directly to the clipboard from Vim:

Of course you can be more specific, and put ranges like numbers in if you like (this writes the six lines from line 5 to 10 into the clipboard):

It’s worth remembering that xclip needs to be able to talk to your X session to get the data in there. Not a problem locally, but if you’re running Vim remotely you need to make sure you’ve got X11-forwarding enabled over your SSH connection.