How do you auto format code in Visual Studio?

To format a selection: Ctrl+K, Ctrl+F

To format a document: Ctrl+K, Ctrl+D

See the pre-defined keyboard shortcuts. (These two are Edit.FormatSelection and Edit.FormatDocument.)

Note for macOS

On macOS, use the CMD ⌘ key instead of Ctrl:

  • To format a selection: CMD ⌘+K, CMD ⌘+F
  • To format a document: CMD ⌘+K, CMD ⌘+D

For Visual Studio 2010/2013/2015/2017/2019

  • Format Document (Ctrl+K,Ctrl+D), i.e. press&hold Ctrl, press&release K then tap D as it is a sequence
  • Format Selection (Ctrl+K,Ctrl+F)

Toolbar Edit -> Advanced (If you can't see Advanced, select a code file in solution explorer and try again)

Your shortcuts might display differently to mine as I am set up for C# coding but navigating via the toolbar will get you to your ones.

If it isn't working, look for errors in your code, like missing brackets which stop auto format from working


I have installed an extension named "Format document on Save" which formats the whole document every time you save it.

For installing it in Visual Studio 2015 or Visual Studio 2017, on Tools just click the "Extensions and Updates...":

Enter image description here

And then just go to "Online" at the left panel and search for "Format document on save":

Enter image description here


  1. Go to menu ToolsExtensions & Updates and type "productivity" in search:

    1

  2. Install 'Productivity Power Tools 2015'

  3. Restart Visual Studio.

  4. Go to menu ToolsOptionsProductivity Power ToolsPower Commands and check "Format document on save":

    2

Note: In VS2022 we don't have power commands.

  • If anyone want to have "Format document on save" and "Remove and sort using on save" install Mads Kristensen extension for VS2022 https://marketplace.visualstudio.com/items?itemName=MadsKristensen.CodeCleanupOnSave
  • After installing this extension it will automatically "Format document on save", "Remove and sort using on save" and "Apply file header preferences".
  • If we want to customize default settings click on "Configure Code Cleanup" menu item to add/remove any available fixers. enter image description here