views:

166

answers:

3

When I open a new line (via 'o') my cursor jumps to a correctly indented position on the next line. On the other hand, entering insert mode while my cursor is on a blank line doesn't move my cursor to the correctly indented location.

How do I make vim correctly indent my cursor when entering insert mode (via i) on a blank line?

+3  A: 

Well this actually wasn't as bad as I thought it would be. One way to enable this is to add the following to your ~/.vimrc

"smart indent when entering insert mode with i on empty lines
function! IndentWithI()
    if len(getline('.')) == 0
        return "\"_ddO"
    else
        return "i"
    endif
endfunction
nnoremap <expr> i IndentWithI()

It simply checks for an empty line when you hit 'i' from insert mode. If you are indeed on an empty line it will delete it and open a new one, effectively leveraging the working 'open line' behavior.

Note: "_ before the dd makes sure that your register doesn't get wiped

TheDeeno
nice. that always bugged me.
michaelmichael
+3  A: 

cc will replace the contents of the current line and enter insert mode at the correct indentation - so on a blank line will do exactly what you're after.

I believe that the behaviour of i you describe is correct because there are many use cases where you want to insert at that specific location on a blank line, rather than jumping to wherever vim guesses you want to insert.

scomar
Well my solution will make 'i' behave that way only when the line is empty - so just one use case. 'i' will behave normally in all other situations. That being said, cc is built in and more appropriate imo. Accepting
TheDeeno
what I love about vim is no matter how long you use it, you can still learn new stuff every day. I use dd, yy, and c with other modifiers extensively every day, never occured to me to try cc. +1
Matt Briggs
A: 

well this saved me a LOT of trouble, thank you both for the answer and the question!

papas
papas, glad it helped you out. Just an fyi, a statements like this are more appropriate in comments. Also, be sure to up vote if you haven't already.
TheDeeno