Search code examples
vimindentationcopy-pastepasteauto-indent

How to correctly indent text when using `put` in Vim


I'm having trouble when putting text in Vim.

Say I want to paste my /* Comment */ line below the $('table').append line...

/* Comment */

for (var i=1; i<=lineLength ; i++) {
    $('table').append('<tr></tr>');
    for (var j=1; j<=lineLength; j++) {
    $('table tr:nth-last-child(1)').append('<td></td>');
    }
}

In most text editors, my workflow would be

  1. Select /* Comment */, hit cut.
  2. Move cursor to end of first line of code and hit return.
  3. Text editor auto-indents, and I just hit paste.

i.e.

/* Comment */

for (var i=1; i<=lineLength ; i++) {
    $('table').append('<tr></tr>');
    | <==Pipe is position of cursor before paste; pasted lines are inserted here.
    for (var j=1; j<=lineLength; j++) {
    $('table tr:nth-last-child(1)').append('<td></td>');
    }
}

But with vim, it seems like I have to do this:

  1. Move to /* Comment */ line, hit dd.
  2. Move to $('table').append line, hit p.

New code:

for (var i=1; i<=lineLength ; i++) {
        $('table').append('<tr></tr>');
/* Comment */. <== Comment is not correctly indented.
        for (var j=1; j<=lineLength; j++) {
        $('table tr:nth-last-child(1)').append('<td></td>');
        }
    }
  1. Manually fix incorrectly indented code.

Vim auto-indents fine when I start a new line with o, so it seems like it should also handle putting onto a new line.... Is there a command that will let me put new lines of code with the correct indentation?


Solution

  • :nnoremap p p`[v`]=
    

    taken from https://github.com/sickill/vim-pasta.