Dane O'Connor
Dane O'Connor

Reputation: 77278

Vim: Smart indent when entering insert mode on blank line?

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?

Upvotes: 55

Views: 11977

Answers (3)

Dane O'Connor
Dane O'Connor

Reputation: 77278

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 "\"_ccO"
    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 cc makes sure that your register doesn't get wiped

Upvotes: 14

Trevor Powell
Trevor Powell

Reputation: 1174

On an empty line, to enter insert mode correctly indented, you can simply use s.

Note that s is a synonym for cl, so if you're not actually on an empty line, it'll end up deleting a single character and not indenting. In that case, you're better off using cc, as sml suggested some 18 months ago. But I've frequently improved my score at VimGolf by using this shortcut, so thought I'd mention it. ;)

Upvotes: 10

sml
sml

Reputation: 2320

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.

Upvotes: 102

Related Questions