按下<Tab>并应用自动缩进时的Vim选项卡大小


22

我决定将标签的大小从4更改为2,因为为什么不呢?任何其他想要查看代码的人都可以使用他们的首选项。

但是,有一个问题。

如果我按下Tab键,它将插入2,但是Vim的自动缩进仍然是4。我要如何更改为2?

另一个无关的问题:哪种缩进样式最适合C和类似语言?我一直在使用1TBS,但有很多选择。他们中的任何一个更专业或更喜欢吗?

Answers:


17

尝试将“ shiftwidth” 设置为与“ tabstop” 相同的值。更好的是,如果您使用的Vim版本足够新,请将' shiftwidth' 设置为0,它将默认设置为' tabstop'。


这就是我想要的。目前在设置ts为2、4或8 之间争论
user341814 2014年

我在非代码文件上使用8,根据语言以及倾向于发生多少嵌套使用2或4。
Heptite

我目前只做C语言。
user341814 2014年

33

Vim缩进选项

Vim主要使用3种设置作为缩进大小:

  • tabstopts::当Vim在您打开的文件中遇到制表时,它会将制表符显示为{ts}空格(请参见tabstop帮助,或输入:help tabstopVim)。
  • softtabstopsts:编辑文件并按Tab键时,Vim使用此设置来定义插入的表格的宽度(请参见softtabstop帮助,或键入:help softtabstopVim)。
  • shiftwidthsw:缩进时,无论是使用自动缩进东西或通常Vim使用的空格数>><<命令。正如Heptite所注意到的,这就是您在此特定情况下要寻找的东西。Vim的最新版本确实允许您不定义该选项,而是shiftwidth采用由定义的值tabstop。非常方便(请参阅shiftwidth帮助)。

因此,例如,如果您使用以下设置:

set sts=4
set ts=2
set sw=8

这些将产生以下行为:

  1. 在文件中插入表格会产生4个空格的缩进。
  2. 当您tabstop将其设置为2时,这实际上相当于2个表格。这相当容易检查,只需使用listlistchars选项即可显示表格。
  3. 如果使用缩进一行>>,则缩进宽度将为8个空格(因此,基于tabstop值,相当于4个表格的形式,与上面相同)。

在此处输入图片说明

Vim缩进建议(来自Vim文档)

tabstop帮助(:help tabstop在Vim中):

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.

我个人主要使用第二种解决方案,具有2个空格的列表。

set ts=2
set sts=2
set et     "expand tabs to spaces

-1

根据http://vim.wikia.com/wiki/Indenting_source_code的介绍,“ filetype plugin indent on”命令将使程序使用位于Vim安装的indent子目录中的特定于文件类型的缩进脚本。该页面还指出,“ cindent”在C和C ++文件中自动使用,并且不需要您手动使用该命令。

我对Vim不太熟悉,因为我只是偶尔使用它进行一些基本的文本编辑,但是我会尝试手动发出“ cindent”命令,以对该代码使用Vim的默认自动缩进大小。如果这样不起作用,您可以尝试使用“ filetype plugin indent on”并自行编辑脚本以获得所需的缩进。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.