4

我曾经在 Vim 中有 8 个空格的制表符。然后我改为 4 个空格,但现在每当我在更改为 4 个空格之前编写的一些代码中添加一行时,即使一切都很好地排列,它也会给我一个缩进不匹配错误。有没有办法避免这个问题?

4

4 回答 4

10

你做过:%retab……吗?

于 2009-05-19T02:03:03.600 回答
10

您是否仅更改了 tabstop 选项?

我使用 4 个空格(当我点击制表符时用空格填充,以插入实际的制表符命中ctrl-v tab)。以下是来自 .vimrc 的选项卡相关设置:

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

当您用空格填充制表符时,您将始终插入空格而不是制表符,并且您的代码将始终看起来相同。

当您使用选项卡时,每个工具都会以不同的方式显示选项卡,您最终会花时间设置应为选项卡 (8、4、3.5) 显示多少空间,而不是进行生产性工作。

或选择其中之一(来自 vim 7.1 help 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.
于 2009-05-19T02:04:06.703 回答
3

对于 python 代码,您可能最好使用以下内容:

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

这样,您仍然使用“行业标准”的 8 个空格选项卡,但您不会将它们中的任何一个放入您的文件中。这也应该使您的旧代码保持干净,尽管您必须重新检查并手动移动所有剩余的内容。你肯定也想 :retab 一切。

如果你想用 4 个空格缩进替换所有内容

:set tabstop=4
:retab
:set tabstop=8

这将使用每个选项卡 4 个空格的空格重新缩进所有内容,并使您恢复正常的默认值。

显然,这取决于意见,但在我的书中,使用选项卡设置为您在 cat 文件时获得的任何内容之外的任何内容都是在自找麻烦。

于 2009-05-19T02:20:14.690 回答
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 个空格。如果您打算为开源项目做出贡献,您可能需要考虑进行更改。

为了在 eol 处删除空格,我还要更加整洁

nnoremap <leader>wd :%s/\s\+$//<cr>
于 2009-05-19T05:06:57.167 回答