自动缩进:smartindent 和 indentexpr

Autoindent : smartindent and indentexpr

当我编辑 Python 文件时,例如:

def my_func():
    print('Something')
    <-- CURSOR IS HERE

我想通过键入 # 添加注释,该行自动重新缩进到行的开头:

def my_func():
    print('Something')
#<-- CURSOR IS HERE

我发现这是 smartindent 选项的影响,所以要修复它,我只需要 运行 :set nosi (或在我的 .vimrc 中禁用它)。

但是在Vim的帮助中,在:h 'smartindent'中,你可以读到:

When 'cindent' is on or 'indentexpr' is set, setting 'si' has no effect.

但是我的 indentexpr 选项设置如下:

:set indentexpr?
indentexpr=GetPythonIndent(v:lnum)

我当然应该完全避免使用 smartindent 选项,因为它看起来是一个旧功能,并且设计为仅适用于 C 风格的语言;

但我想知道为什么 smartindent 在我编辑 python 文件时确实有一些效果,考虑到帮助中写的内容?

是的,它确实按照您解释的方式运行。

以我为例 :echo GetPythonIndent(v:lnum) returns -1

:h indentexpr 有以下解释行为的文字。

 The expression must return the number of spaces worth of indent. It
 can return "-1" to keep the current indent (this means 'autoindent' is
 used for the indent).

当我们设置 si 时,它将接管 ai

现在 :h si 建议解决方法:

:inoremap # X^H#

其中 ^H 输入为 Ctrl + V Ctrl + H

我相信您会有比所提供的解决方法更好的解决方案