Vim在使用python-mode插件时,对Python代码的缩进出现错误

6
如下屏幕录像所示,我演示了在给Python代码添加注释时Vim的奇怪行为。在Demo 1和Demo 2之间,我只是在不同的缩进级别(在类定义内部)开始了注释行。

enter image description here

演示 2

enter image description here

问题:

正如屏幕录像结束时所演示的那样,在插入模式下只输入:将使缩进正确。

理想的解决方案应该实现以下内容:

当开始一行注释时,请正确保留缩进级别;


1
请给我看一下你的vimrc文件,特别是缩进键、缩进表达式和已安装的插件。 - mattn
@mattn,这似乎是由于“set smartindent”不兼容引起的问题?我只需删除此设置后,上述问题就不再存在了。 - llinfeng
啊,看起来smartindent生效了。如果你不记得设置选项,可以通过:verbose set smartindent确认设置在哪里。如果你想禁用它的filetype=python,可以使用autocmd FileType python setlocal nosmartindent - mattn
4
可能是 Vim自动删除Python注释的缩进 的重复问题。 - dlmeetei
我同意这是一个重复的问题。我应该删除这个问题吗?@dlmeetei - llinfeng
2个回答

6
这似乎是vim设置问题。从原始的vim开始,每次创建新行时都没有缩进。如果我在我的home目录中创建一个名为.vimrc的文件,即~/.vimrc,并在文件中添加

filetype indent plugin on

我得到了预期的缩进行为。这对你有用吗?


2

我的解决方案

我注释掉了以下这行代码,问题得到了解决。之后也没有对注释进行任何奇怪的更正。

set smartindent

Vim的其他信息:

为了缩进,以下是设置:

filetype plugin on
filetype indent on
set autoindent

此外,已经确认python-mode没有问题。无论使用还是不使用python-modeset smartindent都会出现问题。
初步结论是:set smartindent与我的折叠方法不兼容。这样的设置放在C:/vim/vimfiles/ftplugin/python.vim中。
setlocal formatoptions=crnqj

以下是使用的字符对应关系,但似乎没有任何问题。

  • c: Auto-wrap comments using textwidth, inserting the current comment leader automatically.

  • r: Automatically insert the current comment leader after hitting <Enter> in Insert mode.

  • n: When formatting text, recognize numbered lists. This actually uses the 'formatlistpat' option, thus any kind of list can be used. The indent of the text after the number is used for the next line. The default is to find a number, optionally followed by '.', ':', ')', ']' or '}'. Note that 'autoindent' must be set too. Doesn't work well together with "2". Example:

    1. the first item
       wraps
    2. the second item
    
  • q: Allow formatting of comments with "gq". Note that formatting will not change blank lines or lines containing only the comment leader. A new paragraph starts after such a line, or when the comment leader changes.

  • j: Where it makes sense, remove a comment leader when joining lines.

参考更好的解决方案

简而言之,当编辑Python脚本时所观察到的情况并不仅适用于“Python文件类型”,而是与符号#(也称为“哈希”)有关。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接