How to paste in a new line with vim?

Viewed 70931

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?

14 Answers

Using this plugin: https://github.com/tpope/vim-unimpaired

]p pastes on the line below

[p pastes on the line above

advantages:

  • works on all yanked text (word, line, character, etc)
  • indents the pasted text to match the indentation of the text around it
  • 2 keystrokes instead of 3 and much "easier" strokes
  • fast

If you wanted to stay in the insert mode, you can do o ctrl+o p

  • o – insert mode and go to the new line
  • ctrl+o – run a single command like in normal mode
  • p – paste

It's three keystrokes but you stay in insert mode and also o ctrl+o is quite fast so I personally treat it as 2.5 keystrokes.

If you want to paste in a new line and still keep indentation, create this mapping:

nnoremap <leader>p oq<BS><Esc>p

Prerequisite: you have leader mapped and you have set autoindent in your .vimrc.

Explanation: a new line is created with 'o', 'q' is typed and then back-spaced on (to keep indentation), and 'esc' brings you back to normal mode where you finally paste.

If you also want to end in insert mode, it is possible to paste while in insert mode using CTRL-R ". https://stackoverflow.com/a/2861909/461834

Still three keystrokes, but no escape, and you save a keystroke if you want to end in insert anyway.

I use the following mapping in my Neovim config:

nnoremap <leader>p m`o<ESC>p``
nnoremap <leader>P m`O<ESC>p``

A little explanation:

  • m`: set a mark in the current cursor position.
  • o<Esc>p: create a new line below and paste the text in this line
  • O<Esc>P: create a new line above and paste the text in this line
  • ``: put the cursor in the original position

See :h mark for more information about marks in Vim.

Related