如何在Vim更改制表位后避免缩进错误?

5

我以前在Vim中使用8个空格作为制表符。然后我改成了4个空格,但现在每当我添加一行代码到之前使用8个空格的代码中时,尽管一切都对齐得很好,它仍会给出缩进不匹配的错误。有没有什么方法可以避免这个问题?


1
这里举个例子会更好。 - sykora
4个回答

11

你尝试过执行 :%retab 命令吗?


运行得非常顺利。 - arqam

10

你只更改了tabstop选项吗?

我使用4个空格(按下tab键时填充空格,要插入实际的制表符,请按下ctrl-v tab)。这是我的.vimrc文件中与tab有关的设置:

" tabs
set tabstop=4
set shiftwidth=4
set expandtab

如果你用空格填充制表位,你总是会插入空格,这样你的代码看起来始终如一。

当你使用制表位时,每个工具都会以不同方式显示制表位,你最终会花费时间设置应该为制表位显示多少个空格(8、4、3.5),而不是进行有意义的工作。

或从vim 7.1帮助tabstop中选择以下选项之一:

    Note: Setting 'tabstop' to any other value than 8 can make your file
    appear wrong in many places (e.g., when printing it).


    There are four main ways to use tabs in Vim:
    1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4
       (or 3 or whatever you prefer) and use 'noexpandtab'.  Then Vim
       will use a mix of tabs and spaces, but typing <Tab> and <BS> will
       behave like a tab appears every 4 (or 3) characters.
    2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use
       'expandtab'.  This way you will always insert spaces.  The
       formatting will never be messed up when 'tabstop' is changed.
    3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a
       |modeline| to set these values when editing the file again.  Only
       works when using Vim to edit the file.
    4. Always set 'tabstop' and 'shiftwidth' to the same value, and
       'noexpandtab'.  This should then work (for initial indents only)
       for any tabstop setting that people use.  It might be nice to have
       tabs after the first non-blank inserted as spaces if you do this
       though.  Otherwise aligned comments will be wrong when 'tabstop' is
       changed.

3

对于Python代码,您最好使用以下内容:

:set tabstop=8
:set shiftwidth=4
:set expandtab

那么你仍然使用“行业标准”的8个空格制表符,但你不需要将它们放入文件中。这样可以保持原有代码的整洁性,尽管你需要经过一段时间手动将所有内容向左移动。你肯定也想要做适当的:retab操作。
如果你想用4个空格缩进替换全部内容,请执行:
:set tabstop=4
:retab
:set tabstop=8

这将使用每个制表符4个空格重新缩进所有内容,并将您恢复到合理的默认设置。

显然,这是有争议的,但在我的看法中,使用除了cat文件时得到的制表符之外的任何其他制表符都会带来麻烦。


或者不要使用真正的制表符,而是用空格填充。无论你使用多少个8或4,只要保持一致即可。 - stefanB
顺便问一下,为什么你会在Python中使用不同的缩进? - stefanB
顺便提一下,我建议使用“set smarttab”。 - kcwu
唉,我讨厌用空格缩进的代码。如果Python能够忽略空格,像原帖作者遇到的问题就不会发生了。 - John Millikin

2

最好的可视化不匹配的方法是使用 :set list 命令,它会显示空格问题。

set listchars=tab:>-,trail:-,nbsp:+ "This is terminal friendly but you can make fancy
set list

我认为这是Python编辑的必要设置,特别是当空格缩进成为常规时。尤其是当文件由同事编辑时更是如此。我还仔细检查了“代码布局”下的样式指南。在http://www.python.org/dev/peps/pep-0008/中指定了一个名为python -tt的选项,如果您混用制表符和空格,它将抛出警告和错误。您可以将其纳入单元测试中。看起来PEP推荐使用4个空格作为新代码的标准。如果您打算贡献到开源项目中,则可能需要考虑更改。另外,为了更加整洁,我删除了行尾的空格。
nnoremap <leader>wd :%s/\s\+$//<cr>

小提示:无论是空格还是制表符,都可以通过为它们设置特殊的高亮规则,在使用语法高亮时使其突出显示。 - user55400

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