tags:

views:

304

answers:

3

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?

+5  A: 

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 are suitable for you, eg:

noremap p p`[
carl
Is there a way to use marks more safely, so that it doesn't destroy something I happen to have in that register? Maybe some other register that isn't normally used at all - I'm not sure what's available or customary.
Wahnfrieden
Sorry, what I meant in my comment was, I'd like to save that as a preset command so it's less to type.
Wahnfrieden
See the revised answer.
carl
Note when you repeat using . the mapping is ignored. Is that a vim bug, or is there a way to honor the mapping? This is especially useful when P rather than p is used, as Shift-P is awkward to repeat
pixelbeat
@pixelbeat I think there's a repeat.vim which makes . more powerful/intelligent. Might help you.
Wahnfrieden
A: 

'k' ? (as in the up arrow)

If you use 'p' to paste text below the current line, the cursor will be on the first line of the pasted content. Typing 'k' in command mode takes you to the line above the start of the pasted content.

LES2
Please re-read my question.
Wahnfrieden
p pastes after cursor. it doesn't have to be in next line. it depends on how you selected block to copy (v vs. shift-v). -1
depesz
+2  A: 

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.

Steve K
This is a great explanation, thank you. I'll experiment with this.
Wahnfrieden