Skip to content

VS Code: Set Tab Size per File Type

VS Code Set Tab Size per File Type

In VS Code, the default tab size is set to 4 spaces.

But if you want different tab sizes for different file types, you’ll need to change some settings.

For example, let’s say you want the tab to be 4 spaces in HTML files but 2 spaces in JavaScript files.

In this guide, I’ll walk you through how to set the tab size based on the file type.

Let’s get started! 🚀

🎥 Prefer a video instead? I got you covered:

Tab Size per File Type

Open the settings.json file by pressing down CTRL + SHIFT + P and run the Preferences: Open User Settings (JSON) command.

We’re going to start off by adding the following settings:

// settings.json

"editor.tabSize: 4", // default value
"editor.detectIndentation": false,

editor.detectIndentation is helpful when working with files that use different indentation styles.
If you set it to false, VS Code won’t automatically detect the indentation style from the file.
Instead, it will use the settings we’ll configure next.

Let’s say you want to have 2-space tabs in JavaScript files, 4-space tabs in HTML files, and 2-space tabs in Markdown files.
This translates into the following code:

// settings.json

"[javascript]": {
    "editor.tabSize": 2
},
"[html]": {
    "editor.tabSize": 4
},
"[markdown]": {
    "editor.tabSize": 2
},

As you can notice, both the javascript and the markdown types have the same tab size values.

We can group them to make them more concise and save some space.

// settings.json

"[javascript][markdown]": {
    "editor.tabSize": 2
},
"[html]": {
    "editor.tabSize": 4
},

Bit of a Problem

A problem you might face when writing these configurations is that the language names like javascript, markdown and html, might not always be obvious.

Let’s take the following example:

I want to add another file type txt.

If I set it like this 👇, it won’t work because VS Code doesn’t recognize the txt as language.

// ❌
"[txt]": {
    "editor.tabSize": 10
},

To find out the name of the language that VS Code supports, you can press CTRL + SHIFT + P and run the command Preferences: Configure Language Specific Settings.

In the dropdown menu, you’ll see the names of all the languages supported by VS Code.

If we search for “text”, you’ll see that the language for txt files is actually plaintext.

So, the correct code in this case is:

// âś…
"[plaintext]": {
    "editor.tabSize": 10
},

The complete and final code should look like this:

"editor.tabSize": 4,
"editor.detectIndentation": false,
"[javascript][markdown]": {
    "editor.tabSize": 2
},
"[html]": {
    "editor.tabSize": 4
},
"[plaintext]": {
    "editor.tabSize": 10
},

Happy coding đź’ś


Let me know what you think about this article in the comments section below.

If you find this article helpful, please share it with others and subscribe to the blog to support me, and receive a bi-monthly-ish e-mail notification on my latest articles.   
  

Comments