Do you want to automatically indent your code in Visual Studio Code?
Visual Studio Code is a free, Microsoft-made code optimized editor for Windows, OS X, and Linux, with support for IntelliSense (an intelligent code completion system), debugging, and GIT. Over a few short years, the editor has made itself popular among developers, with half a million active users and more than two million installation done across the world.
This article is going to show you how to indent your code, both automatically and manually, in Visual Studio Code
Automatically indent your code in VSCode
Since version 1.14 released back in June 2017, automatic indentation feature has been added into Visual Studio Code codebase.
Automatic indentation feature will be really useful for new developers, since they should be copying and pasting code from StackOverflow quite a lot.
Auto-indentation on Visual Studio Code is disabled by default, you would have to set the
editor.autoIndent flag to
true in the configuration in order to enable it. To do that without touching the JSON configuration files, follow the steps below to change global user settings in GUI mode:
Ctrl+Shift+Pto open Command Palette. 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. Changes are saved automatically and applies to all opened files as well.
Indent your code in VSCode on demand
To be able to properly indent your code anytime you want, you would need to install a linter or formatter or beautifier extension which supports your programming language. The linter should work like a spell checker, highlight errors, bugs and provide remediation guidance.
Here is a non-comprehensive list of linters for various programming languages you can install from inside VSCode Marketplace.
- markdownlint : Markdown
- Python : Python
- Kotlin : Kotlin
You can find more extensions by searching in the VSCode Marketplace.
Once you get the appropriate extension installed, you can press Shift + Alt + F to automatically format the document. Alternatively, press Ctrl + Alt + P to open Command Palette and search for Format Document achieve the same result.
Auto indent on save in VSCode
From version 1.6, Visual Studio Code added support for automatic format upon document saving with
editor.formatOnSave flag. To enable the feature, follow the steps below.
Ctrl+Shift+Pto open Command Palette. Type in settings and select Open User Settings. Alternatively, press Ctrl + ,.
- In Search settings box, input format on save to search for settings related to document formatting. Check the box below Editor: Format On Save that says A formatter must be available, the file must not be saved after delay, and the editor must not be shutting down
- Similarly, you can also enable Format on Paste, which automatically format pasted content as well as indentation.