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

后端 未结 3 1568
遥遥无期
遥遥无期 2020-12-23 13:35

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 l

相关标签:
3条回答
  • 2020-12-23 14:24

    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 讨论(0)
  • 2020-12-23 14:30

    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

    0 讨论(0)
  • 2020-12-23 14:33

    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.

    0 讨论(0)
提交回复
热议问题