VS Code Per Language Indentation

As a general rule, when I write code I indent with spaces (not tabs) and use a tabstop of 4; these are configured as global settings in VS Code. I think it provides a pretty clear view of things without being overly wasteful of space; it still blows my mind that Vim’s default tabstop is a massive 8. That being said, certain languages have their own conventions, and I’m not one to want to buck those or write code in a non-standard format. For example, I’ve recently been doing more web development, so I’ve been spending time working with HTML, CSS, and JavaScript (okay, mostly JavaScript and then CSS and HTML.) Those are 3 languages which all typically use a tabstop of 2 characters.

Since I’m not insane, I typically use an opinionated formatter on my code so that it gets cleaned up to some standard or another every time I hit save. I use Black for Python and started using the venerable Prettier for web-related things. Prettier will automatically change all of my tabs to a width of 2 for me, but it was still a bit annoying to write new code with 4 space and then always have it reformatted upon hitting save. What I really needed was a means by which to override my global settings based on the language so that writing new code in a file that has been formatted by Prettier will align automatically. Of course, this was fairly simple to do.

UI Method

The first way I did this was through the UI. I used the Command Palette with Cmd/Ctrl + Shift + p. Then I searched for “preferences” and selected Configure Language Specific Settings:

Then I simply had to select the language to configure, such as JavaScript:

Finally, in those settings I just had to adjust the Tab Size setting:

JSON Method

Going through the UI was fine, though it was annoying to do for multiple languages. It’s also difficult to use the UI and get a big picture of which languages have unique settings. I also needed to configure Prettier as the default formatter for a handful of things. In the end, it was easier for me simply go back to the Command Palette, search for “settings” and then open the JSON file that contains my VS Code settings. There I configured the settings for several languages to adjust both the default formatter, enable format on save, and set the tab size:

It’s also simple to scroll through this JSON file and see which languages have which configuration. My most recent version of my VS Code settings after these changes is available at this updated Gist.