How to format a code or files in Visual Studio Code

It is a short tutorial on how to format a code in Visual Studio Code or VScode.

Here is a sequence of steps to format a code in Visual

First way

  • In Visual Studio Code Editor, Right-click on it
How do you format code in visual studio code

There are two ways you can format

  • Format Document
  • Format Selection

Format Document:

It formats the entire file, You can also use the shortcut code Shift+Alt+F.

Format Selection:

you can select a block of code or an entire file code that formats the selected code.

You can use Ctrl+K Ctrl+F.

It works in Windows.

Sometimes shortcuts are not working in Windows.

  • Shift + Option +F in Mac OS
  • Ctrl + Shift + I in Linux and Unix

These are default settings and shortcuts in Visual Studio Code

How to customize format settings in VSCode?

you can still customize these settings in the User or Workspace settings

Here are the steps to change default settings.

  • Go to File Menu
  • Select Preferences and Choose Settings
  • Below popup is shown to the user
Visual Studio Code default settings
  • Select the workspace tab
  • Change and check or uncheck different settings
  • On saving the settings, It saves the settings configuration to .vscode/settings.json.

Alternatively, You can update the below settings in .vscode/settings.json.

settings.json:

{
  "beautify.onSave": true,

  "editor.formatOnSave": true,
  "prettier.singleQuote": true,
  "editor.formatOnType": true,

  // This property allows beautifying extension files
  "beautify.JSfiles": ["html", "json", "xml", "java", "ts"]
}

Here are the settings configured

beautify.onSave: This allows you to beautify the file before saving the file. beautify is a plugin that installs default. editor.formatOnSave: This also does format on saving the file editor.formatOnType: This formats line on line break using semicolon. beautify.JSfiles: This contains the list of file extensions that can be used to format the files.

Wrap Up

To Wrap Up, Short tutorials on How to format code in VSCode, change default settings, and shortcut commands in Windows, Linux, and Mac OS.