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.
ftplugin
In ~/.vim/ftplugin/python.vim:
setlocal shiftwidth=2 softtabstop=2 expandtab
And don't forget to turn them on in ~/.vimrc
:
filetype plugin indent on
(:h ftplugin
for more information)
autocommand
In ~/.vimrc
:
autocmd FileType python setlocal shiftwidth=2 softtabstop=2 expandtab
You can replace any of the long commands or settings with their short versions:autocmd
: au
setlocal
: setl
shiftwidth
: sw
tabstop
: ts
softtabstop
: sts
expandtab
: et
I would also suggest learning the difference between tabstop
and softtabstop
. A lot of people don't know about softtabstop
.
edit your ~/.vimrc
, and add different file types for different indents,e.g. 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