Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paste in Vim without moving the cursor

Tags:

vim

Often I need to paste something into several adjacent lines, at the same or similar positions. It's a pain to have to move the cursor back to the beginning of the pasted contents every time, when moving on to the next line. How can I paste (as in, the command 'p') without moving the cursor? Or, how can I quickly get the cursor back to where it was before pasting?

like image 230
aehlke Avatar asked Oct 19 '09 06:10

aehlke


People also ask

How do we paste the clipboard contents before the cursor vim?

Press y to copy, or d to cut the selection. Move the cursor to the location where you want to paste the contents. Press P to paste the contents before the cursor, or p to paste it after the cursor.

How do I paste after a line in Vim?

Options: 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.

Can you paste in vim?

Pasting in VimOnce you have selected text in Vim, no matter whether it is using the yank or the delete command, you can paste it in the wanted location. In Vim terminology, pasting is called putting and the function is utilized with the p command. Using this command pastes the selected text after the cursor.


2 Answers

The safest way without destroying a register is to do the following:

p`[ 

If you want to create a shortcut, just use any of vim's map functions that is suitable for you, eg:

noremap p p`[ 
like image 149
carl Avatar answered Sep 20 '22 12:09

carl


Whenever I have a sequence of steps to repeat several times I record a macro, which is trivially easy in Vim. The general method is

  1. Position the cursor where you want to make the first change.
  2. Type qx to start recording keystrokes.
  3. Make the first edit.
  4. Move the cursor to the position where the second edit should begin.
  5. Hit q again to quit recording.
  6. Type @x to replay the macro and make the next edit. The @ command takes a count so you can repeat the edit as many times as you want with one command.

So in your case, the entire sequence of keystrokes to record the macro might be

qxp`[jq 

and 5@x to replay it five times for a total of 6 changes.

Note that the character after the first q is a register to record the macro into and it can be any letter, not just x. Just be careful your macros doesn't yank text into the register presently being recording into, it makes a real mess of things!

Macros can be arbitrarily long and complex. They can contain Ex mode commands and even call other macros.

like image 35
Steve K Avatar answered Sep 22 '22 12:09

Steve K