neovim 自动缩进的细微差别

dsc*_*ose 8 vim neovim

我刚刚从 vim 切换到 neovim。以下 vim 配置设置通过缩进获得我想要的行为:

\n
set tabstop=4\nset shiftwidth=4\nset softtabstop=4\nset autoindent\nset backspace=indent,eol,start\n
Run Code Online (Sandbox Code Playgroud)\n

这里的相关部分是自动缩进:

\n
set autoindent\n
Run Code Online (Sandbox Code Playgroud)\n

在每个换行符上,这会导致 vim 匹配上一行的缩进:

\n
def demo_autoindent():\n    a = 'This line was manually indented'\n\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\n
Run Code Online (Sandbox Code Playgroud)\n

的声明a手动缩进一步,但第二行自动缩进到同一级别。在这里,我用一系列\xc2\xb7字符表示自动缩进。

\n

Neovim 符合这种行为。然而,Neovim 试图在块方面变得更聪明,或者在本例中用 python 声明字典:

\n
def example_neovim():\n    b = {\n\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\n
Run Code Online (Sandbox Code Playgroud)\n

请注意,Neovim 并未自动缩进该行。如果有,它将与 的声明具有相同的 4 个空格缩进b。相反,Neovim 额外添加了两个缩进,使总数达到 12 个空格。

\n

显然,它的目的是添加进一步的缩进:

\n
def example_neovim_intention():\n    c = {\n\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\xc2\xb7\n
Run Code Online (Sandbox Code Playgroud)\n

如何将 Neovim 配置为:

\n
    \n
  1. 匹配 vim 的行为,只是自动缩进到同一级别。
  2. \n
  3. 在声明例如字典时添加一个(而不是双)额外缩进。
  4. \n
\n

小智 4

我面临着完全相同的问题,我使用 VIM 很长一段时间,最近我切换到 NeoVim。

除“python”之外的所有其他语言的自动缩进效果都很好。我发现这个文档非常有用: https: //neovim.io/doc/user/indent.html#ft-python-indent

:h ft-python-indent
Run Code Online (Sandbox Code Playgroud)

NeoVim 将检查此变量g:python_indent,如果未定义,将创建默认变量,它会是这样的(NeoVim 0.8.2):

{
  'disable_parentheses_indenting': v:false,
  'closed_paren_align_last_line': v:true,
  'searchpair_timeout': 150,
  'continue': 'shiftwidth() * 2',
  'open_paren': 'shiftwidth() * 2',
  'nested_paren': 'shiftwidth()'
}
Run Code Online (Sandbox Code Playgroud)

更改这些属性continueopen_paren如下closed_paren_align_last_line所示。

{
  'disable_parentheses_indenting': v:false,
  'closed_paren_align_last_line': v:false,
  'searchpair_timeout': 150,
  'continue': 'shiftwidth()',
  'open_paren': 'shiftwidth()',
  'nested_paren': 'shiftwidth()'
}
Run Code Online (Sandbox Code Playgroud)

另一种方法(推荐)

这可以更轻松地解决奇怪的缩进问题。

设置nvim-treesitter/nvim-treesitter并打开 tree-sitter 的缩进功能。

:h ft-python-indent
Run Code Online (Sandbox Code Playgroud)

  • nvim-treesitter 缩进仍然有很多问题。没有任何缩进比它提供的缩进更烦人。 (3认同)