How to change indentation in Visual Studio Code?
Asked Answered
S

24

780

For every typescript file visual studio code uses an auto indentation of 8 spaces. This is a bit too much for my taste but I can't find where to change it.

Maybe it's available as a setting but under a different name as I can't find anything related to indentation.

UPDATE

I'm currently using the Prettier code formatter and that solves all formatting problems by auto formatting on save (if there is no syntax error)

Sickler answered 9/12, 2015 at 8:40 Comment(2)
See Also: How can I customize the tab-to-space conversion factor?Diatom
related: How can I convert tabs to spaces and vice versa in an existing file?Termor
B
538

You can change this in global User level (all your projects if not deliberately set) or Workspace level (only for the current working project).

Open the settings: Click the gear on the bottom left, then click Settings as shown below.

Settings on VS Code menu

Then, do the following 2 changes: (type tabSize in the search bar)

  1. Uncheck the checkbox of Detect Indentation
  2. Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS. Haha :))

vscode set tabsize

Brinton answered 16/12, 2019 at 9:4 Comment(4)
For those wondering, this will automatically reformat all files in your project, not just new ones you create. You might have to restart vs code for changes to take effect.Irresponsive
Both of these settings were already good to go on my installation (box checked, spaces set as I like it; and this is on a brand new angular project, so no copy/pasted code to screw things up), but it still didn't take, at least for the typescript files. I added a language specific setting as described by Martin Schneider above, so hopefully that'll work.Malherbe
Update on my previous comment: It seems angular generated a '.editorconfig' file as well that I hadn't noticed before. In that file, the property 'indent_size' was set to 2 when I wanted 4. That was probably the original culprit. I've set that to 4 and removed the language-specific setting.Malherbe
@Malherbe I just ran into this, too. I had the Angular project nested, and their config file says it is the root. That makes the EditorConfig extension stop looking for parent configs in higher directories :(Hell
U
1079

In the toolbar in the bottom right corner you will see a item that looks like the following:

screenshot with "Spaces: 4" highlighted

After clicking on it you will get the option to indent using either spaces or tabs. After selecting your indent type you will then have the option to change how big an indent is. In the case of the example above, indentation is set to 4 space characters per indent. If tab is selected as your indentation character then you will see Tab Size instead of Spaces

If you want to have this apply to all files and not on an individual file basis, then override the Editor: Tab Size and Editor: Insert Spaces settings in either User Settings or Workspace Settings depending on your needs

Edit 1

To get to your user or workspace settings go to Preferences -> Settings. Verify that you are on the User or Workspace tab depending on your needs and use the search bar to locate the settings. You may also want to disable Editor: Detect Indentation as this setting will override what you set for Editor: Insert Spaces and Editor: Tab Size when it is enabled

Umbrian answered 24/7, 2016 at 21:20 Comment(10)
Changing editor.tabSpaces does not change the spacing in all files. It only changes it for future-created files. There's still no solution for fixing all files in one action.Bores
Not responsive to the question which is how to change the indent size.Renteria
@JacobStamm, if you set editor.detectIndentation to false - at least you don't need to click every time you open old file to change it to different (valid) value as described below by RmuesiMayer
This is super unintuitive. I already have indentation set to use spaces. Why do I need to click on the spaces option to get to a second, hidden menu to set the number of spaces? Every other editor I've used is one click on the indentation details in the status bar and there's a number of spaces option. In VS Code I need to look this up on Stack Overflow because the menu I want is hidden behind an option I'm not trying to change.Touraco
it always seems to revert back to the default of 4 space every time i create a new file?!?!Homework
@BugWhisperer changing the spacing as shown in the screenshot in the answer only affects the current file. Did you try updating your User or workspaces settings as suggested?Umbrian
@JacobStamm you can also use the "Convert Indentation to Spaces" and "Convert Indentation to Tabs" commands to apply the change to the file that you are currently editing.Umbrian
Looks like v1.40 has fix the bug that count'd effect all files, "editor.detectIndentation": false, "editor.insertSpaces": false, "editor.tabSize": 4,Melany
this doesn't set the global configuration, just the current fileStoltz
@Umbrian Does not work for me. Opening a file with tabs of size=2, selecting all text, pressing F1 and selecting the Convert Indentation to Spaces, pressing F1 again and selecting Convert Indentation to Tabs still keeps tabs size=2 (when on the settings is set to 4).Fad
B
538

You can change this in global User level (all your projects if not deliberately set) or Workspace level (only for the current working project).

Open the settings: Click the gear on the bottom left, then click Settings as shown below.

Settings on VS Code menu

Then, do the following 2 changes: (type tabSize in the search bar)

  1. Uncheck the checkbox of Detect Indentation
  2. Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS. Haha :))

vscode set tabsize

Brinton answered 16/12, 2019 at 9:4 Comment(4)
For those wondering, this will automatically reformat all files in your project, not just new ones you create. You might have to restart vs code for changes to take effect.Irresponsive
Both of these settings were already good to go on my installation (box checked, spaces set as I like it; and this is on a brand new angular project, so no copy/pasted code to screw things up), but it still didn't take, at least for the typescript files. I added a language specific setting as described by Martin Schneider above, so hopefully that'll work.Malherbe
Update on my previous comment: It seems angular generated a '.editorconfig' file as well that I hadn't noticed before. In that file, the property 'indent_size' was set to 2 when I wanted 4. That was probably the original culprit. I've set that to 4 and removed the language-specific setting.Malherbe
@Malherbe I just ran into this, too. I had the Angular project nested, and their config file says it is the root. That makes the EditorConfig extension stop looking for parent configs in higher directories :(Hell
M
361

To change the indentation based on programming language:

  1. Open the Command Palette (CtrlShiftP | macOS: P).
  2. Type and select: Preferences: Configure Language Specific Settings... (command id: workbench.action.configureLanguageBasedSettings).
  3. Select a programming language (for example TypeScript).
  • If Settings menu is opened (since 1.66.0):
    4. Press to place the cursor right beside the language filter (e.g. @lang:typescript).
    5. Type Tab Size and enter your preferred value in the text box.

  • If settings.json file is opened:
    4. Add this code:

    "[typescript]": {
        "editor.tabSize": 2
    }
    

See also: VS Code Docs

Matisse answered 14/8, 2017 at 9:43 Comment(6)
How (where) does one use the command id? I don't see "Configure Language Specific Settings" under File-Preferences.Addictive
@AlanBaljeu You can use command ids e.g. to define keyboard shortcuts. There is no "Configure Language Specific Settings" under File > Preferences, because step 2 is not a menu entry, but the text in italics should be entered into the input field that appears after performing step 1.Matisse
how do you change based on file extension?Unabridged
@Unabridged see Language identifier and "Adding a file extension to a language" below.Matisse
"Add this code"... to where? These instructions didn't open a text file.Germinant
@GrantBirchmeier the latest VS Code update 12 days ago has changed the behavior. I have updated my answer.Matisse
A
67

Code Formatting Shortcut:

VSCode on Windows - Shift + Alt + F

VSCode on MacOS - Shift + Option + F

VSCode on Ubuntu - Ctrl + Shift + I

You can also customize this shortcut using preference setting if needed.

column selection with keyboard Ctrl + Shift + Alt + Arrow

Atalya answered 31/7, 2018 at 7:36 Comment(2)
Shift + Alt + F changed all the indents in my file from 8 spaces to my default 4 spaces. Just what I was looking for :)Alsatian
Ctrl + Shift + I really helpedQuillan
K
63

You might also want to set the editor.detectIndentation to false, in addition to Elliot-J's answer.

VSCode will overwrite your editor.tabSize and editor.insertSpaces settings per file if it detects that a file has a different tab or spaces indentation pattern. You can run into this issue if you add existing files to your project, or if you add files using code generators like Angular Cli. The above setting prevents VSCode from doing this.

Kitsch answered 24/8, 2017 at 22:30 Comment(0)
R
37

In my case "EditorConfig for VS Code" extention is overriding VSCode settings. If you have it installed, then check .editorconfig file in the root folder of the project.

Here is an example config. The "indent_size" sets the number of spaces for a tab.

# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
Retriever answered 10/5, 2018 at 10:32 Comment(0)
O
22

How to turn 4 spaces indents in all files in VS Code to 2 spaces

  • Open file search
  • Turn on Regular Expressions
  • Enter: ( {2})(?: {2})(\b|(?!=[,'";\.:\*\\\/\{\}\[\]\(\)])) in the search field
  • Enter: $1 in the replace field

How to turn 2 spaces indents in all files in VS Code to 4 spaces

  • Open file search
  • Turn on Regular Expressions
  • Enter: ( {2})(\b|(?!=[,'";\.:\\*\\\/{\}\[\]\(\)])) in the search field
  • Enter: $1$1 in the replace field

NOTE: You must turn on PERL Regex first. This is How:

  • Open settings and go to the JSON file
  • add the following to the JSON file "search.usePCRE2": true

Hope someone sees this.

Orthopedics answered 3/1, 2020 at 22:16 Comment(1)
Specifically for VS Code, there is also an extension for converting 4 to 2 spaces.Peeling
R
15

Simplified explanation with pictures for those that googled "Change indentation in VS Code"

Step 1: Click on Preferences > Settings

enter image description here

Step 2: The setting you are looking for is "Detect Indentation", begin typing that. Click on "Editor: Tab Size"

enter image description here

Step 3: Scroll down to "Editor: Tab Size" and type in 2 (or whatever you need).

enter image description here



Changes are automatically saved

enter image description here

Example of my changes

enter image description here

Renz answered 7/10, 2019 at 3:4 Comment(0)
D
13

To set all existing files and new files to space identation to 2 just put it in your settings.json (in the root of json):

"[typescript]": {
  "editor.defaultFormatter": "vscode.typescript-language-features",
  "editor.tabSize": 2,
  "editor.insertSpaces": true,
  "editor.detectIndentation":false
}

You can add the language type of the configuration:

"[javascript]": {
  "editor.tabSize": 2,
  "editor.insertSpaces": true,
  "editor.detectIndentation":false
} 
Duncan answered 30/8, 2019 at 14:21 Comment(1)
These days I use prettier.js and the js plugin as it takes care about spacing and other re aligning long lines as well as most anything else.Sickler
R
8

Setting the indentation in preferences isn't allways the solution. Most of the time the indentation is right except you happen to copy some code code from other sources or your collegue make something for you and has different settings. Then you want to just quickly convert the indentation from 2 to 4 or the other way round.

That's what this vscode extension is doing for you

enter image description here

Revelatory answered 7/10, 2020 at 17:36 Comment(0)
G
7

Step 1: Open settings.json in vscode

Step 2: Add the lines as below for the programming language (an example is below)

For typescript and javascript

"editor.detectIndentation": false,
"[typescript]": {
        "editor.defaultFormatter": "vscode.typescript-language-features",
        "editor.tabSize": 2,
        "editor.insertSpaces": true,
        "editor.detectIndentation":false
 },
"[javascript]": {
    "editor.tabSize": 2,
    "editor.insertSpaces": true,
    "editor.detectIndentation":false
}
Gayn answered 22/6, 2021 at 11:18 Comment(1)
Open settings.json in vscode The way to do that is ctrl+shit+p and type settings or cmd+shift+p on Mac. There is a global settings.json and a workspace settings.json. I prefer using prettier.js as my formatter because it has more style settings.Sickler
U
6

Problem: The accepted answer does not actually fix the indentation in the current document.

Solution: Run Format Document to re-process the document according to current (new) settings.

Problem: The HTML docs in my projects are of type "Django HTML" not "HTML" and there is no formatter available.

Solution: Switch them to syntax "HTML", format them, then switch back to "Django HTML."

Problem: The HTML formatter doesn't know how to handle Django template tags and undoes much of my carefully applied nesting.

Solution: Install the Indent 4-2 extension, which performs indentation strictly, without regard to the current language syntax (which is what I want in this case).

Uzzi answered 22/10, 2018 at 5:32 Comment(0)
E
4

I wanted to change the indentation of my existing HTML file from 4 spaces to 2 spaces.

I clicked the 'Spaces: 4' button in the status bar and changed them to two in the next dialog box.

I use 'vim' extension. I don't how to re-indent without vim

To re-indent my current file, I used this:

gg

=

G
Explorer answered 10/9, 2018 at 2:40 Comment(0)
G
3

Check tabWidth if you are using a formatter, that was the issue in my case. It represents the number of spaces used in tabs.

enter image description here

Glossitis answered 9/9, 2022 at 16:37 Comment(0)
P
1

Adding on: yes, you can use the bottom-right UI to configure the space settings. But if you have existing code that's not formatted to the new spacing, then you can right-click anywhere within the file and click Format Document. Took me a while to figure this out until I stumbled on this issue.

Format Document menu

Pergola answered 15/10, 2018 at 16:53 Comment(2)
Ok I installed Ruby, Ruby Formatter, and Rufo as described. Changed from 2 to 4 spaces. Then right-click and Format. Nothing changed for me.Insulting
I have "Spaces: 4" in my toolbar, I have a JSON file where most of it is formatted to 4-characters. But when I right click and select "Format Document", it all gets reindented to 2-characters. I have "detectIndentation" set to false. I don't get it....Audre
T
1

For me it was docs-markdown andDocs Authoring Pack. Microsoft's many modules messing with each other yet again! Disabled the extensions and now good to go again 😀

Tabling answered 28/7, 2021 at 2:34 Comment(0)
H
1

I like these settings for indentation you can modify them according to need.

You can open VScode setting.json file by typing CTRL+SHIFT+P and paste below the JSON setting

setting.json

"[javascript]": {
  "editor.defaultFormatter": "vscode.typescript-language-features",
  "editor.formatOnSave": true,
  "editor.tabSize": 4,
  "editor.insertSpaces": false,
  "editor.detectIndentation": false,
  "editor.wrappingIndent": "deepIndent",
  "editor.autoIndent": "full"
},
"[typescript]": {
  "editor.defaultFormatter": "vscode.typescript-language-features",
  "editor.formatOnSave": true,
  "editor.tabSize": 4,
  "editor.insertSpaces": false,
  "editor.detectIndentation": false,
  "editor.wrappingIndent": "deepIndent",
  "editor.autoIndent": "full"
}
Honora answered 11/7, 2022 at 19:53 Comment(0)
A
1

If youre trying to change your default spacing, you need to change the "editor.insertSpaces" (boolean) key in settings.json. Otherwise this only works per file.

"editor.tabSize" will allow you to set the tab size you want (2, 4, 6 etc)

Avert answered 14/1 at 3:37 Comment(0)
P
0

The Problem of auto deintending is caused due to a checkbox being active in the settings of VSCode. Follow these steps:

  1. goto preferences

  2. goto settings

  3. search 'editor:trim auto whitespace' EDITOR Picture

  4. Uncheck The box

Petua answered 11/9, 2020 at 23:13 Comment(0)
N
0

The following search-and-replace regex changes the number of spaces per indentation level from 4 to 2 in existing files. It's relatively easy to understand, reliable, and doesn't require installing anything.

Instructions

  • Press CtrlH (or ⌥⌘F on macOS).
  • Make sure regex matching is on by clicking on the .* button in the search popup or pressing AltR (or ⌥⌘R on macOS).
  • In the Find field, enter ^(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?(?:( ) )?
  • In the Replace field, enter $1$2$3$4$5$6$7$8$9
  • Finally press CtrlEnter (or ⌘Enter on macOS) to apply to the current file.

You could also use this in the Search pane on the left to do this across all files in your project. However, note that this should only be run once per file. It will mess up the indentation of files that already use 2 spaces.

 


Extra Credit: How It Works

The way the regular expression works is it matches groups (?: ... ) of four spaces at a time at the beginning ^ ... of each line, only capturing ( ... ) the first two spaces. Each indentation level is optional ... ?, so it works for as many indentation levels as the pattern is repeated and there are in each line. Then it replaces the whole pattern with only the captured spaces $1, $2, ..., effectively replacing every four-space indentation level with two spaces.

This pattern only works up to 9 indentation levels (I'm not sure if $10 would work, but if so this could be expanded indefinitely).

Extra Extra Credit: Extending

You could adapt the pattern to decrease the number of spaces per indentation level in a file from any original number to another lower target number.

Put the target number of spaces inside the inner parenthesis. Then, put the remaining original number of spaces in the outer parenthesis, so the total number of spaces in the pattern is the original.

For example, if you want to change the indentation level from 6 to 4, repeat this search pattern as many times as you like:

^(?:( ) )? or ^(?:( {4}) {2})?

And use the same number of $1, $2 in the replacement pattern.

Nike answered 10/12, 2021 at 7:20 Comment(0)
P
0

First, check if you have installed "EditorConfig for VS Code". It was overriding my editor settings. I spent all day correcting this problem.

In the project find .editorconfig file and ones changed there it will work.

Provost answered 9/3, 2022 at 14:10 Comment(0)
D
0

With VSCode 1.75 (Jan. 2023), indentation is also customizable on VSCode terminals, not just VSCode views.

See issues 170432: "Add a terminal tab stop size (editor.tabSize) setting"

When a tab is printed in the terminal, it has a tab size of 8 spaces, regardless of the tab size setting.

Therefore, PR 170733 adds a new setting:

terminal.integrated.tabStopWidth: The number of cells in a tab stop

Disbelieve answered 10/1, 2023 at 21:46 Comment(0)
A
0

Place these lines into .editorconfig:

[*]
indent_style = space
indent_size = 2

Then install "Prettier - Code formatter" in VS Code

Then press Option + Shift + F on Mac, or Alt + Shift + F on Windows

Aspia answered 20/3 at 12:55 Comment(0)
J
0

I had a hard time to set it for Go Lang.

Finally I was able to enforce space instead of tab and 2 tab size by below steps.

  1. Command Pallette -> Preferences Open User Settings (JSON)

  2. Then insert below config

{
  ...,
  "[go]": {
    "editor.tabSize": 2,
    "editor.insertSpaces": true,
    "editor.detectIndentation":false,
  },
  ...
}
Joyce answered 8/4 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.