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


当前回答

编辑~/。Vimrc,并为不同的缩进添加不同的文件类型,例如。我想html/rb缩进2个空间,和js/coffee文件缩进4个空间:

" by default, the indent is 2 spaces. 
set shiftwidth=2
set softtabstop=2
set tabstop=2

" for html/rb files, 2 spaces
autocmd Filetype html setlocal ts=2 sw=2 expandtab
autocmd Filetype ruby setlocal ts=2 sw=2 expandtab

" for js/coffee/jade files, 4 spaces
autocmd Filetype javascript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype coffeescript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype jade setlocal ts=4 sw=4 sts=0 expandtab

参考:根据文件类型设置Vim空白参数

其他回答

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

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

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

编辑~/。Vimrc,并为不同的缩进添加不同的文件类型,例如。我想html/rb缩进2个空间,和js/coffee文件缩进4个空间:

" by default, the indent is 2 spaces. 
set shiftwidth=2
set softtabstop=2
set tabstop=2

" for html/rb files, 2 spaces
autocmd Filetype html setlocal ts=2 sw=2 expandtab
autocmd Filetype ruby setlocal ts=2 sw=2 expandtab

" for js/coffee/jade files, 4 spaces
autocmd Filetype javascript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype coffeescript setlocal ts=4 sw=4 sts=0 expandtab
autocmd Filetype jade setlocal ts=4 sw=4 sts=0 expandtab

参考:根据文件类型设置Vim空白参数

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

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

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

vim.opt_local.foldmethod  = 'marker'

我使用了一个用C语言写的工具autotab。它分析加载文件的前几千行,并确定Vim参数shiftwidth, tabstop和expandtab的值。

这是使用gcc -O autotab.c -O autotab进行编译的。与Vim集成的说明在顶部的注释头中。

Autotab相当聪明,但有时会让人困惑,特别是使用不同的缩进样式不一致地维护。

如果一个文件明显使用制表符或制表符和空格的组合来缩进,Autotab将通过考虑诸如跨连续行内部元素的对齐方式(如注释)等因素来确定所使用的制表符大小。

它适用于各种编程语言,并且可以容忍不遵守缩进增量的“带外”元素,例如C预处理指令、C语句标签,更不用说明显的空行了。

虽然你可以使用缩进插件或手动使用设置来配置Vim的缩进,但我建议使用一个名为Vindect的python脚本,当你打开一个python文件时,它会自动为你设置相关设置。使用这个技巧可以使Vindect的使用更加有效。当我第一次开始编辑别人用各种缩进样式(制表符vs空格和空格数量)创建的python文件时,这令人难以置信地沮丧。但是Vindect和这个缩进文件一起

还建议:

pythonhelper python_match python_ifold