Vim: Smart indent when entering insert mode on bla

2020-05-14 13:46发布

问题:

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?

回答1:

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.



回答2:

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



回答3:

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. ;)