vim

How to preserve indent after pressing Esc in Vim


I have set autoindent
I go to a line, press A and <CR> which gets me to the next line and inserts an indent. However if I press Esc the cursor jumps to the beginning of the line and the indent is gone.
I have to go about and press tabs to get to the right place again.

I know the help says:

If you do not type anything on the new line except <BS> or CTRL-D and then type
<Esc>, CTRL-O or <CR>, the indent is deleted again.

Is there a way to disable this, or at least a workaround?


Solution

  • Alright, I figured this out.

    Based on Edan Maor's answer, S or cc should enter insert mode with the proper level of indentation.
    ...except when it doesn't :)

    This works under two circumstances.

    I found that the best solution is to have this is my .vimrc

    set autoindent
    set indentexpr=GetIndent()
    
    function GetIndent()
       let lnum = prevnonblank(v:lnum - 1)
       let ind = indent(lnum)
       return ind
    endfunction
    

    Now when I press S or cc, it will insert the same indent as on the previous non-blank line.