Copying content from vim to Mac OS clipboard

May 27, 2014

As a heavy user of vim and Mac OSX I very often need to copy something from vim to the OS clipboard. This can be easily accomplished with the mouse, but I hate to touch it.

You can copy within the terminal using the pbcopy builtin command. That said we can write the following function:

function! CopyToOSClipboard() range
  exec(":silent !cat %:p | sed -n " . a:firstline . "," . a:lastline . "p | pbcopy")

A brief explanation of what is going on:

  • silent is used to not show the process output into the screen
  • I’m using sed to select between the lines of the range
  • and finally I’m feeding pbcopy with the sed output

Now lets map it to <Leader><Leader>c in normal and visual mode:

nnoremap <Leader><Leader>c :call CopyToOSClipboard()<CR>
vnoremap <Leader><Leader>c :call CopyToOSClipboard()<CR>

Now if you hit <Leader><Leader>c the current cursor line will be copied to the clipboard. Of course you can also go into visual mode, select some lines and press <Leader><Leader>c to copy more than one line.

IMPORTANT Because this function works in the file of the current vim buffer, not in the buffer memory the file needs to be saved.

comments powered by Disqus