开发者

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

开发者 https://www.devze.com 2023-01-02 15:29 出处:网络
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

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.

开发者_如何学JAVA

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


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消