Sunday, March 20, 2011

copy selection to OS X system clipboard in Vim

Method 1:
To copy the output in Mac OSX Terminal to clipboard, you can use the the command pbcopy:

Add this to your ~/.vimrc:

" ctrl-x for cut
vmap <C-x> :!pbcopy<cr>
" ctrl-c for copy
vmap <C-c> :w !pbcopy<cr><cr>

Then, on your desktop application, press command-v to paste.

Note: pbcopy is a system command. For example:
# cat fileName.txt | pbcopy

Method 2:
Download and install MacVim

For MacVim and Windows Gvim, simply add the following to your ~/.vimrc:

set clipboard=unnamed

Now all operations such as yy, D, and P work with the clipboard. No need to prefix them with "* or "+.

Method 3:
If the clipboard is enabled, you can copy a selected region to the clipboard by hitting:

"*y
or
"+y

Note: In X11, Vim's "* is PRIMARY, "+ is CLIPBOARD, and SECONDARY doesn't get a named register. (Not that anybody uses it...).

To see if it is enabled, execute vim --version and look for +clipboard or -clipboard. For example, it's not enabled by default on my 10.6.0 box:

# vim --version | grep clipboard
-clipboard

For MacVim and Windows Gvim, simply add the following to your ~/.vimrc:

set clipboard=unnamed

Now all operations such as yy, D, and P work with the clipboard. No need to prefix them with "* or "+.

Method 4:
If you are using MacPorts you can upgrade your VIM to include clipboard support via:

port install vim +x +x11

Now you use the "+ register to yank your text directly to your Mac clipboard. Works like a charm.

Reference:
http://stackoverflow.com/questions/677986/vim-copy-selection-to-os-x-clipboard

No comments: