Changing Vim indentation behavior by file type

Could someone explain to me in simple terms the easiest way to change the indentation behavior of Vim based on the file type? For instance, if I open a Python file it should indent with 2 spaces, but if I open a Powershell script it should use 4 spaces.


You can add .vim files to be executed whenever vim switches to a particular filetype.

For example, I have a file ~/.vim/after/ftplugin/html.vim with this contents:

setlocal shiftwidth=2
setlocal tabstop=2

Which causes vim to use tabs with a width of 2 characters for indenting (the noexpandtab option is set globally elsewhere in my configuration).

This is described here: http://vimdoc.sourceforge.net/htmldoc/usr_05.html#05.4, scroll down to the section on filetype plugins.


Use ftplugins or autocommands to set options. (:h ftplugin for more information)

In ~/.vim/ftplugin/python.vim:

setlocal sw=2 sts=2 et

And don't forget to turn them on in ~/.vimrc

filetype plugin indent on

Or in ~/.vimrc

au FileType python setl sw=2 sts=2 et

I would also suggest learning the difference between 'ts' and 'sts'. A lot of people don't know about 'sts'.


edit your ~/.vimrc , and add different file types for different indents,eg I want html/rb indent for 2 spaces, and js/coffee files indent for 4 spaces:

" 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

refer to: Setting Vim whitespace preferences by filetype

链接地址: http://www.djcxy.com/p/49532.html

上一篇: 如何修复vim中破坏的自动缩进

下一篇: 按文件类型更改Vim缩进行为