Saturday, March 5, 2011

How to paste in a new line with vim?

I often have to paste some stuff on a new line in vim. What I usually do is:

o<esc>p

Which inserts a new line and puts me in insertion mode, than quits insertion mode, and finally pastes.

Three keystrokes. Not very efficient. Any better ideas?

Solution 0:
You can paste a buffer in insert mode using <C-R> followed by the name of the buffer top paste. The default buffer is ", so you would do

o<C-R>"

I found that I use <C-R>" very often and bound that to <C-F> in my vimrc:

inoremap <C-F> <C-R>"

Solution 1:
Use yy to yank the whole line (including the end of line character). p will then paste the line on a new line after the current one and P (Shift-P) will paste above the current line.

Solution 2:
Make a mapping: then it's only one or two keys:

:nmap ,p o<ESC>p
:nmap <F4> o<ESC>p

Solution 3:
The function version of the mapping (unnecessary really, but just for completeness):

:nmap <F4> :call append(line('.'), @")<CR>

" This one may be a little better (strip the ending new-line before pasting)
:nmap <F4> :call append(line('.'), substitute(@", '\n$', '', ''))<CR>

:help let-register
:help :call
:help append()
:help line()
:help nmap

Reference:
http://stackoverflow.com/questions/1346737/how-to-paste-in-a-new-line-with-vim

No comments: