I usually work on js files and php files. My js files require 2 spaces tab, whereas my php requires 4. How can I make vim dynamically change that depending on the file type I'm working on?


Putting these in your .vimrc should do the trick:

augroup FileTypeSpecificAutocommands
    autocmd FileType javascript setlocal tabstop=2 softtabstop=2 shiftwidth=2
    autocmd FileType php setlocal tabstop=2 softtabstop=2 shiftwidth=2
augroup END

You should also use expandtab to convert tabs into spaces, I think. Also, you might wanna check out this blogpost.

Also, if you don't mind splitting up your vimrc in modular files, you can put the following commands in ~/.vim/after/ftplugin/javascript.vim and ~/.vim/after/ftplugin/php.vim

setlocal tabstop = softtabstop = shiftwidth = 2
  • ideology is kind of a big word to be put in a vim forum don't you think? 😏
    – abbood
    Mar 3 '18 at 6:46
  • what should I use then?
    – klaus
    Mar 3 '18 at 7:46
  • 1
    'Ideology' sounds fine to me. It's a war after all...us against them! ;)
    – B Layer
    Mar 3 '18 at 11:34
  • This kind of settings should be in a ftplugin rather than in autocommands because with autocommands the filetype is tested for each autocommand which is not efficient and this is also replicating something vim already does automatically. Also, if you stick with using autocommands it is usually a good idea to put them in an augroup.
    – statox
    Mar 4 '18 at 17:55
  • @statox, fixed it. Sorry, it took so long. I was visiting through all my answers to check if I could add something new.
    – klaus
    Feb 17 '19 at 17:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.