简体   繁体   English

Vim:在空行上进入插入模式时智能缩进?

[英]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. 当我打开一个新行(通过'o')时,我的光标跳到下一行的正确缩进位置。 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? 在空行上进入插入模式(通过i)时,如何使vim正确缩进光标?

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. cc将替换当前行的内容并在正确的缩进处进入插入模式 - 因此在空行上将完全按照您的要求进行操作。

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. 我认为,行为i你的描述是正确的,因为有您想要在特定位置上的空白行插入,而不是跳跃到哪里VIM猜测要插入许多用例。

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 实现此目的的一种方法是将以下内容添加到〜/ .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. 当您从插入模式点击“i”时,它只会检查空行。 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 注意:“_在cc之前确保您的注册表没有被删除

On an empty line, to enter insert mode correctly indented, you can simply use s . 在空行上,要正确缩进进入插入模式,您只需使用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. 请注意, scl的同义词,因此如果您实际上不是空行,它最终会删除单个字符而不是缩进。 In that case, you're better off using cc , as sml suggested some 18 months ago. 在那种情况下,你最好使用cc ,就像sml在18个月前提出的那样。 But I've frequently improved my score at VimGolf by using this shortcut, so thought I'd mention it. 但是我经常使用这个快捷方式提高我在VimGolf的分数,所以我想提到它。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM