Search code examples
vimindentation

Auto indenting fails when using the "cc", "S", or "]p" commands on a blank line in Vim


If I try cc or S when the cursor (| below) is in the following position:

public function blah()
{
    var i = 0;
|
    i++
    return i;
}

It stays in the first column instead of moving under the letter v in var. Pasting with ]p also pastes starting from column 1.

My setup (in MacVim) is: autoindent, smartindent, nocindent, and indentexpr=, if that helps.

According to the following SO questions, correct indentation should be possible:

In the last post, @trVoldemort had the same issue (see the comments to the second answer).


Solution

  • Turn on cindent...

    :set cindent
    

    This works for indenting with "cc" and "S", as long as the language has similar indentation to C (or support for cindent).

    With this, the smart-indent paste (]p) still doesn't work on an empty line, however. For that, remap ]p as follows:

    :nnoremap ]p oX<Esc>]pk"_dd
    

    This will create a new line at the correct indentation before doing the re-indent paste. Then it goes back and deletes that line, making sure not to overwrite the default buffer.

    You can also remap the alternative versions of the smart-indent paste:

    :nnoremap ]P OX<Esc>]pk"_dd
    :vnoremap ]p "_xkoX<Esc>]pk"_dd
    :vnoremap ]P "_xkoX<Esc>]pk"_dd