How to use FileType in Vim

vimvimrc

In most cases, I want to use tabstop=4 while editing files. But for some types of file, like xml file, I want to use tabstop=2.

I added

au filetypedetect FileType xml,html,xhtml,javascript set tabstop=2 softtabstop=2 shiftwidth=2

in my .vimrc file. It works if I am editing only one file. But if I am editing multiple files, it cannot set the tab stops correctly for all the buffers. It seems the file type is detected and set only on startup, and never change since.

I want the FileType set each time I switch the buffer. How can I do that?

Best Answer

I am not sure why your version is not working, but I am able to do this using the call option and putting the settings in a function like this:

set tabstop=4
set softtabstop=4
set shiftwidth=4

function! setAltPrefs()
    set tabstop=2
    set softtabstop=2
    set shiftwidth=2
endfunction

autocmd FileType xml,html,xhtml,javascript call setAltPrefs()

This should get fired any time a file is loaded into a buffer or the filetype changes. The only catch would be if you change a buffer from one of the custom types back to one that should just be defaults. In that case nothing will change. You would have to setup another function to trigger on all over file types if you need to cover that use case.