vimauto-indent

How can I delete/yank paste in vim and have it indent correctly? (not talking about :paste)


Please note this is NOT related to :paste / :nopaste and the clipboard. I'm talking about copying and pasting entirely within vim (d, y, p).

It is common to copy and paste a block of code from an outer block into an inner block. Unfortunately, the indentation still is at the level of the outer block and I have to indent it afterwards.

What I want to do is to go from:

function foo() {
}
var bar;
var bazz;

to

function foo() {
  var bar;
  var bazz;
}

In vim what I normally do is:

1) go to the line

2) switch to visual mode

3) highlight the rows

4) dd to delete the lines

5) move the cursor up

6) P to paste

7) enter visual mode

8) highlight the rows

9) >> to indent the lines

I want it to automatically indent to the correct location. It would be a much smoother workflow if I didn't need to re-highlight the rows and then indent them manually. In other words, eliminate steps 7-9.

Anybody know of a way to do this?


Solution

  • You can easily make this a keymap that does auto indenting as part of pasting.

    For example,

    nnoremap gp p`[v`]=
    

    Breakdown:

    p to paste text
    `[v`] to select pasted text
    = to autoindent selected text