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") :redraw! endfunction
A brief explanation of what is going on:
silentis used to not show the process output into the screen
- I’m using
sedto select between the lines of the range
- and finally I’m feeding
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.