How to change indentation in Visual Studio Code? - formatting

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)

In the toolbar in the bottom right corner you will see a item that looks like the following:
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

You can change this in global User level or Workspace level.
Open the settings: Click the gear on the bottom left, then click Settings as shown below.
Then, do the following 2 changes: (type tabSize in the search bar)
Uncheck the checkbox of Detect Indentation
Change the tab size to be 2/4 (Although I strongly think 2 is correct for JS. Haha :))

To change the indentation based on programming language:
Open the Command Palette (CtrlShiftP | macOS: ⇧⌘P).
Type and select: Preferences: Configure Language Specific Settings... (command id: workbench.action.configureLanguageBasedSettings).
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

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

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.

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

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.

Simplified explanation with pictures for those that googled "Change indentation in VS Code"
Step 1: Click on Preferences > Settings
Step 2: The setting you are looking for is "Detect Indentation", begin typing that. Click on "Editor: Tab Size"
Step 3: Scroll down to "Editor: Tab Size" and type in 2 (or whatever you need).
Changes are automatically saved
Example of my changes

To set all existing files and new files to space identation to 2 just put it in your settingns.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
}

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

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
}

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).

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

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

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

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 😀

The Problem of auto deintending is caused due to a checkbox being active in the settings of VSCode.
Follow these steps:
goto preferences
goto settings
search 'editor:trim auto whitespace'
Uncheck The box

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.

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.

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"
}

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

Related

Problem with vertical line in vs code indentation

I have this problem: I'm using Vue CLI with Vetur/Volar, and as u can see from the pic, i wish i could see indentation line also between the empty spaces. Vs code automatically indent everything like that by itself in my case, but, with some empty spaces without lines. And (more strange) i have in my project only 'one' file (a FooterPage.vue file as all the other .vue, nothing different) that's indent in the correct way....only in that file... I actually decided to remove indentation line because is frustrating
[enter image description here](https://i.stack.imgur.com/vJIjW.png)
I need the Indentation lines like the Footer vue file from the system and not like the other pic
Try adding this to your user settings.json or your workspace's .vscode/settings.json file:
"[css]": {
"editor.indentSize": 3,
"editor.detectIndentation": false
}

How to auto-indent code in the Atom editor?

How do you auto-indent your code in the Atom editor? In other editors you can usually select some code and auto-indent it.
Is there a keyboard shortcut as well?
I found the option in the menu, under Edit > Lines > Auto Indent. It doesn't seem to have a default keymap bound.
You could try to add a key mapping (Atom > Open Your Keymap [on Windows: File > Settings > Keybindings > "your keymap file"]) like this one:
'atom-text-editor':
'cmd-alt-l': 'editor:auto-indent'
It worked for me :)
For Windows:
'atom-text-editor':
'ctrl-alt-l': 'editor:auto-indent'
The accepted answer works, but you have to do a "Select All" first -- every time -- and I'm way too lazy for that.
And it turns out, it's not super trivial -- I figured I'd post this here in an attempt to save like-minded individuals the 30 minutes it takes to track all this down. -- Also note: this approach restores the original selection when it's done (and it happens so fast, you don't even notice the selection was ever changed).
1.) First, add a custom command to your init script (File->Open Your Init Script, then paste this at the bottom):
atom.commands.add 'atom-text-editor', 'custom:reformat', ->
editor = atom.workspace.getActiveTextEditor();
oldRanges = editor.getSelectedBufferRanges();
editor.selectAll();
atom.commands.dispatch(atom.views.getView(editor), 'editor:auto-indent')
editor.setSelectedBufferRanges(oldRanges);
2.) Bind "custom:reformat" to a key (File->Open Your Keymap, then paste this at the bottom):
'atom-text-editor':
'ctrl-alt-d': 'custom:reformat'
3.) Restart Atom (the init.coffee script only runs when atom is first launched).
Package auto-indent exists to apply auto-indent to entire file with this shortcuts :
ctrl+shift+i
or
cmd+shift+i
Package url : https://atom.io/packages/auto-indent
I prefer using atom-beautify, CTRL+ALT+B (in linux, may be in windows also) handles better al kind of formats and it is also customizable per file format.
more details here: https://atom.io/packages/atom-beautify
You can just quickly open up the command palette and do it there
Cmd + Shift + p and search for Editor: Auto Indent:
This works for me:
'atom-workspace atom-text-editor':
'ctrl-alt-a': 'editor:auto-indent'
You have to select all with ctrl-a first.
This is the best help that I found:
https://atom.io/packages/atom-beautify
This package can be installed in Atom and then CTRL+ALT+B solve the problem.
On Linux
(tested in Ununtu KDE)
There is the option in the menu, under Edit > Lines > Auto Indent or press Cmd + Shift + p, search for Editor: Auto Indent by entering just "ai"
Note: In KDE ctrl-alt-l is already globally set for "lock screen" so better use ctrl-alt-i instead.
You can add a key mapping in Atom:
Cmd + Shift + p, search for "Settings View: Show Keybindings"
click on "your keymap file"
Add a section there like this one:
'atom-text-editor':
'ctrl-alt-i': 'editor:auto-indent'
If the indention is not working, it can be a reason, that the file-ending is not recognized by Atom. Add the support for your language then, for example for "Lua" install the package "language-lua".
If a File is not recognized for your language:
open the ~/.atom/config.cson file (by CTRL+SHIFT+p: type ``open config'')
add/edit a customFileTypes section under core for example like the following:
core:
customFileTypes:
"source.lua": [
"conf"
]
"text.html.php": [
"thtml"
]
(You find the languages scope names ("source.lua", "text.html.php"...) in the language package settings see here)
If you have troubles with hotkeys, try to open Key Binding Resolver Window with Cmd + .. It will show you keys you're pressing in the realtime.
For example, Cmd + Shift + ' is actually Cmd + "
You could also try to add a key mapping witch auto select all the code in file and indent it:
'atom-text-editor':
'ctrl-alt-l': 'auto-indent:apply'
I was working on some groovy code, which doesn't auto-format on save. What I did was right-click on the code pane, then chose ESLint Fix. That fixed my indents.
If you are used to the Eclipse IDE or the Netbeans, you can use the package eclipse-keybindings (https://atom.io/packages/eclipse-keybindings):
This Atom package provides Eclipse IDE key mappings for Atom. Currently, the Eclipse shortcuts are directly mapped to existing Atom commands.
To format all lines from a file, just use: Ctrl+Shift+F.
Ctrl+Shift+i worked for me in PHP under Windows ... but some files did not react. Not being the brightest it took me a while to work out that it was the include files that were the problem. If you are using echo(' ... PHP ...') then the PHP does not get re-formatted. To get over this, create a temporary PHP file, say t.php, copy the PHP part into that, reindent it (Ctrl+Shift+i ... did I mention that?) and then copy the newly reformatted PHP back into the original file. Whilst this is a pain, it does give you correctly formatted PHP.

Intellij comment format

Now, I am using the default configurations, and the "//" is displayed at the first column when I press the "command" + "/", see the second line in the picture.
How can I change configuration to display the "//" at the start of the code and following with a space? Just like the first line.
There is an option in: Code Style > Java > Code Generation > Comment Code
With "Line comment at first column" you can switch between:
//System.out.println("");
// System.out.println("");
So, you don't have a 'space' after comment (in first line), but its close enough :)
Idea 2017.2+
Recent versions of IntelliJ IDEA support adding a space after the line comment. The setting is at the same location.
IntelliJ 2017.2 now does exactly what you want. I'm not sure when this was originally introduced.
Project Settings > Code Style > Java
Change tab to Code Generation, locate Comment Code section
Uncheck "Line Comment at First Column"
Check "Add a space at comment start"
Now when you press Control-/
boolean goodCode = true;
becomes
// boolean goodCode = true;
To fix comments during reformatting, go to file->settings->editor->code style->java->wrapping and braces->keep when reformatting->uncheck "comment at first column"

How to make phpstorm display line numbers by default?

How to make phpstorm display line numbers by default?
Couldn't find that option. It's kind of annoying to turn them on manually for each page.
Settings (or Preferences if you are on Mac) | Editor | General | Appearance and check Show line numbers.
Just now found where is it on Windows. Its View -> Active Editor -> Show Line Numbers (changes only for current document) and File -> Settings -> Editor -> Appearance -> Show Line Numbers (for all documents)
For Mac Version go to PhpStorm -> Preferences in menu.
In the preference window go to IDE settings -> Editor -> Appearance -> Show Line Numbers (To change setting for all documents)
OR if you want to quickly set show line number PER CURRENT WINDOW even easier - right click on the long white column (where breakpoints are set) then select Show Line Numbers.
Red dot on the screenshot is a place where you have to click
All the guys are right. I am just bringing the the current soultion with the images.
Go to File-> Settings
In the box in the top right corner type in line numbers, just below that choose Editor->Appearance, from the right checkboxes, find Show line numbers and check it.
After that hit Apply and OK
That should do the trick.
My version of PhpStorm is 6.0.3
If you're on a Mac:
PhpStorm -> Preferences... -> Editor -> Appearance -> Show Line Numbers
just double tap 'Shift'
and search for 'Line Numbers'
and there you will see a toggle option on or off
In PHPStorm 8 this setting is no longer under 'Appearance' but now in:
File -> Settings -> Editor -> Appearance -> Show line numbers
Follow the below steps:
Click on File->Settings->
In the Settings dialog box Expand Editor under IDE Settings
Click Apperance - > select Show line numbers.
Click Apply->Ok.
Simplest solution for line numbers in php storm..There are many other solutions but i think A big picture a good from 1000 words.
File -> Settings -> Editor -> General -> Appearance
check "Show Line Numbers"
This is the current location as of phpStorm 8.0.2 on Ubuntu 14.04
Settings -> editor | appearance | Show line numbers
Just right click on left side where line numbers generally show, select "show line numbers"
In PHPStorm 2016: File > Settings > Editor > General > Appearance > check "Show line numbers"
By typing command + shift + A you will get a search prompt and write line numbers . Now you can trigger button on or off
For PhpStorm version 9 on Windows.
File→Settings→Editor→General→Appearence then check Show line numbers
in the top right corner is a search button type show line numbers and you will see a toggle option. this way you never have to do it yourself. :)
File->settings->IDE Settings->Editor->Appearance
And just check the "Show line numbers" works with 8.0.1
On the Mac version 8.0.1 has this setting here:
PhpStorm > Preferences > Editor (this is in the second section on the left - i.e. IDE Settings NOT Project Settings) > Appearance > Show line numbers
You should go to: File -> Settings -> Editor -> General -> Appearance -> Show Line Numbers
As of the latest version:
PhpStorm > Preferences.. > Editor > General > Appearance > Show line numbers

Force code formatter in IntelliJ to join lines

I'm trying to force IntelliJ to reformat the code the way Eclipse does it.
When I set a line width to e.g. 120 chars I would like IDE to join line that were broken up to multiple lines (e.g. because the line width was set to 80 chars).
I want to go from here:
int a = 1
+ 2;
To here:
int a = 1 + 2
Is it possible in IntelliJ? I'm looking for the appropriate setting in the formatter but cannot find it. Could someone tell me where I can find it?
This works for me in intellij 8 if i go to:
File -> Settings -> Code Style -> Wrapping -> Binary operations -> set to: 'Wrap if long' or 'Do not wrap'
Then CTRL-ALT-L to reformat the code
Menu -> Edit -> Join Lines (Ctrl+Shift+J)
If your code already contains inappropriate line breaks and you want the formatter to remove them during the reformat,
File -> Settings -> Code Style -> Wrapping and Braces ->
Keep When Formatting -> Line Breaks -> Untick
(at least on IntelliJ 15 based Editors)
For Intellij 2016.2.x I had to deselect this option in the Settings:
Then go back to your code and press CTRL-ALT-L