谁能简单地给我解释一下,根据文件类型改变Vim缩进行为的最简单方法是什么?例如,如果我打开一个Python文件,它应该缩进2个空格,但如果我打开一个Powershell脚本,它应该使用4个空格。


当前回答

就我个人而言,我在.vimrc中使用这些设置:

autocmd FileType python set tabstop=8|set shiftwidth=2|set expandtab
autocmd FileType ruby set tabstop=8|set shiftwidth=2|set expandtab

其他回答

我通常使用expandtab set,但这对makefile不好。我最近补充道:

:autocmd FileType make set noexpandtab

到。vimrc文件的末尾,它可以识别Makefile, Makefile和*。Mk作为makefile文件,不展开制表符。可以推测,您可以扩展它。

今天,你可以尝试editorconfig,也有一个vim插件。这样,您不仅可以在vim中更改缩进大小,而且可以在许多其他编辑器中保持一致的编码风格。

下面是一个简单的编辑配置,如你所见,python文件将有4个缩进空格,而pug模板文件将只有2个。

# 4 space indentation for python files
[*.py]
indent_style = space
indent_size = 4

# 2 space indentation for pug templates
[*.pug]
indent_size = 2

在Lua(对于Neovim用户)中,您可以使用RUNTIMEPATH/ftplugin/*yourfiletype*。Lua选项如下:

vim.opt_local.shiftwidth  = 2
vim.opt_local.tabstop     = 2

只是要确保在引号中使用字符串值。例如:

vim.opt_local.foldmethod  = 'marker'

根据~/.vimrc中的文件后缀放置autocmd命令

autocmd BufRead,BufNewFile   *.c,*.h,*.java set noic cin noexpandtab
autocmd BufRead,BufNewFile   *.pl syntax on

您要查找的命令可能是ts=和sw=

使用ftplugins或autocommands设置选项。

ftplugin

在~ /维姆- ftplugin python。维姆:

setlocal shiftwidth=2 softtabstop=2 expandtab

别忘了打开~/.vimrc:

filetype plugin indent on

(:h ftplugin获取更多信息)

autocommand

在~ / . vimrc:

autocmd FileType python setlocal shiftwidth=2 softtabstop=2 expandtab

我还建议学习tabstop和softtabstop的区别。很多人都不知道softtabstop。