Copying current Vim buffer into clipboard

486 views Asked by At

I am trying to copy Vim's buffer to clipboard and I did the following:

:!cat %|pbcopy # It works perfectly

Then I tried to map this with the leader key (its my first attempt to map something, so please excuse if something silly is found).

:map <leader>c :!cat %|pbcopy # This is not working; vim complains: Not an Editor command

2

There are 2 answers

5
FDinoff On BEST ANSWER

Escape the pipe

:map <leader>c :!cat %\|pbcopy

Also consider using nnoremap to stop recursive mappings and ending the command with <CR> so the command runs automatically.

nnoremap <leader>c :!cat %\|pbcopy<CR>

You also might consider using shellescape just incase the file has spaces or other unusual characters

nnoremap <leader>c :exec '!cat '.shellescape('%').'\|pbcopy'<CR>

Or as Peter Rickner says just use

nnoremap <leader>c :w !pbcopy<cr>
2
benjifisher On

This will work on any system, not just Mac:

:nmap <leader>c :%y+

(I can never remember the difference between the "+ and "* registers.) OTOH, your method will work if you are on a Mac, using a version of vim that does not have GUI support, such as /usr/bin/vi.

:help "+
:help :y