每次我在CSS中添加选择器并按Enter来定义属性时,它最终是这样的:

#selector {
        property: value;
}

(8-space标签)

我如何配置Vim使它像这样:

#selector {
    property: value;
}

(4空间选项卡)


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

这将插入四个空格而不是制表符。空格更“稳定”一点,这意味着缩进的空格文本在浏览器和其他应用程序中显示的效果是一样的。

扩展zoul的回答:

如果你想设置Vim在编辑特定文件类型时使用特定的设置,你会想使用自动命令:

autocmd Filetype css setlocal tabstop=4

这将使制表符显示为4个空格。设置expandtab将导致Vim实际插入空格(它们的数量由制表符控制)当你按下制表符;您可能希望使用softtabstop来使退格键正常工作(也就是说,在使用制表符时减少缩进,而不是总是一次删除一个字符)。

为了做出一个关于如何设置的完全有根据的决定,你需要阅读Vim文档中的tabstop, shiftwidth, softtabstop和expandtab。最有意思的部分在expandtab (:help 'expandtab)下:

There are four main ways to use tabs in Vim: 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 and will behave like a tab appears every 4 (or 3) characters. 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. 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. 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.

更新

如果您在一个特定的项目中工作,我强烈建议使用editorconfig。

它允许您在存储库的根定义一个.editorconfig文件,定义跨存储库的每种文件类型所需要的缩进。

例如:

root = true

[*.css]
charset = utf-8
indent_style = space
indent_size = 4

[*.js]
charset = utf-8
indent_style = space
indent_size = 2

有一个vim插件可以根据你打开的文件的配置文件自动配置vim。

此外,许多其他ide和编辑器都自动支持.editorconfig文件,因此它是不同环境下用户之间协作的最佳选择。

原来的答案

如果你需要经常改变大小,并且你不想把它绑定到特定的文件类型,你可以在你的.vimrc文件上有预定义的命令来快速切换首选项:

nmap <leader>t :set expandtab tabstop=4 shiftwidth=4 softtabstop=4<CR>
nmap <leader>m :set expandtab tabstop=2 shiftwidth=2 softtabstop=2<CR>

这将两组不同的大小映射到键\t和\m。你可以把它重新绑定到任何你想要的键。

要更改一个会话,使用以下命令:

:set tabstop=4

要使更改永久生效,请将其添加到~/。Vimrc或~/.vim/ Vimrc:

set tabstop=4

这将影响所有文件,而不仅仅是css。只影响css文件:

autocmd Filetype css setlocal tabstop=4

正如米夏拉的回答中所述。

本页上的几个答案是对所描述问题的“一次性”修复。这意味着,下次使用vim打开文档时,将返回先前的选项卡设置。

如果有人对永久更改标签设置感兴趣:

在这里找到/打开你的.vimrc -指令 添加以下行:(更多信息在这里) 设置制表符= 4 设置shiftwidth = 4 设置expandtab 然后保存文件并进行测试

作为vim中的一行代码:

:set tabstop=4 shiftwidth=4

对于永久设置,将这些行添加到~/.vimrc:

set tabstop=4
set shiftwidth=4
set expandtab    <-- (optional) 4-spaces instead of Tab indentation

在我的。vim/vimrc (ubuntu bionic下的vim 8.0)中,我有

if has("autocmd")
  filetype plugin indent on
endif

所以添加了这样的行: autocmd文件类型css setlocal tabstop=2 是行不通的。

我创建了。vim/indent文件夹,并添加: css。vim与

set tabstop=2
set shiftwidth=2
set softtabstop=2

它确实有效! 我试着在另一台ubuntu focal和vim 8.1的电脑上,它不工作!

在vim命令模式下,写入:

:set ts=X

X是你想要的新空间长度