Set Vim tab spacing based on the type of file

Now that my buddy Justin is back to using vim, he’s been flooding me
with questions. Loljk, but he did ask about setting the tab spacing based on the
type of file he was working with. Incidentally, this was something I had just
improved in my dotfiles.

Back before I knew any better, I had my tab settings separated into files that
were loaded based on the file’s type. This is great if you have a ton of
configuration for a specific file type and don’t want it polluting your main
vimrc.

It was major overkill just for setting the tab spacing.

A month or so ago, I had noticed in my co-sumo Shane’s dotfiles that he
was doing the same thing but in a single line. Actually multiple lines, one for
each language he wanted to configure differently than the defaults.

For him, it was JavaScript and Go, for me, it’s JavaScript and PHP. For Justin?
Not really sure, evidently he’s too good to publish his dotfiles.

So how’s it work? Pretty simple really. For my use case, I just include the
following in my vimrc:

autocmd FileType javascript setlocal tabstop=2 shiftwidth=2 softtabstop=2
autocmd FileType php        setlocal tabstop=4 shiftwidth=4 softtabstop=4

Boom! JavaScript files can do their thing while PHP files can remain compliant
with the hokum that is the PHP Standards Recommendations.

This approach isn’t limited to just tab spacing, you could set whatever else you
need for the specific file type.

Expect some more vim posts in the near future. Partly because I’ve been
improving my config lately but more importantly, because it’s been 5 minutes
since I’ve told somebody about it 😉

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.