Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto-indent rules for file extension in Visual Studio Code (vscode)?

Is there a way to tell Visual Studio Code to apply specific auto-indent rules for a given file extension? Our current settings.json file is:

{
    "editor.tabSize": 4,
    "editor.insertSpaces": true,
    "files.associations": {
        "**/src/**/*.js": "javascriptreact"
    }
}

I did try the following, but it did not work for me:

{
    "files.associations": {
        "**/src/**/*.js": "javascriptreact",
        "package.json": "json"
    },
    "[javascriptreact]": {
        "editor.insertSpaces": true,
        "editor.tabSize": 4
    },
    "[json]": {
        "editor.insertSpaces": true,
        "editor.tabSize": 2
    }
}

I did experiment with [*.json], but that did not work either.

I am using Visual Studio Code 1.15.0.

like image 845
Andre M Avatar asked Aug 21 '17 23:08

Andre M


People also ask

How do I automatically indent in VSCode?

Type in settings and select Open User Settings. In Search settings box, input indent to search for settings related to indentation. Select full in Editor: Auto Indent section. Automatic indentation is now enabled.


1 Answers

[For simplicity, I'll put the various solutions into an answer.]

Vscode has a handy way to edit language-specific editor settings.

Ctr-Shift-P : Preferences: Configure language specific settings...

and chose your language. Choosing "JavaScript React" will open and create an entry in your settings.json file where you can add javascript react specific editor settings like number of spaces to use for a tab.

Oddly though, the new settings entry is appended to the end of the file while the file is not automatically scrolled to that point. So scroll to the end of the settings.json file to find your new language-specific entry. Into that you can put things like :

 "[json]": {
    "editor.detectIndentation": false,
    "editor.tabSize": 4,
    "editor.insertSpaces": true
 }

Note that "editor:detectIndentation" is defaulted to true so you must change it to false for tabSize and insertSpaces to have any effect. Making the above change within the settings.json file will immediately show that it is working within that json file (see the Spaces: # item in the lower right corner of the editor).

However, these settings will not change your existing spacings within a file, but new tabs will reflect your changes...

Unless you have a conflicting extension that sets the same editor settings. I knew the "prettier" extension would do so. The OP @Andre M reports that the extension "beautify" also conflicts with spaces for tabs.

like image 69
Mark Avatar answered Sep 28 '22 07:09

Mark