How do you format code in Visual Studio Code (VSCode)?

3,324,677

Solution 1

The code formatting is available in Visual Studio Code through the following shortcuts:

  • On Windows Shift + Alt + F
  • On Mac Shift + Option + F
  • On Linux Ctrl + Shift + I

Alternatively, you can find the shortcut, as well as other shortcuts, through the 'Command Palette' provided in the editor with Ctrl +Shift+ P (or Command + Shift + P on Mac), and then searching for format document.

For unsaved snippets

  1. Open command palette (Win: F1 or Ctrl+Shift+P)

  2. Find "Change Language Mode"

  3. Select language e.g. json. By now syntax should be highlighted.

  4. Format document (e.g. Open Command Palette -> "Format Document")

Unformat

  1. Select text
  2. Command Palette -> Join Lines

'Show the pics'

enter image description here enter image description here

Solution 2

Code Formatting Shortcut:

Visual Studio Code on Windows - Shift + Alt + F

Visual Studio Code on MacOS - Shift + Option + F

Visual Studio Code on Ubuntu - Ctrl + Shift + I

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

Code Formatting While Saving the File:

Visual Studio Code allows the user to customize the default settings.

If you want to auto format your content while saving, add the below code snippet in the work space settings of Visual Studio Code.

Menu FilePreferencesWorkspace Settings

{
    // Controls if the editor should automatically format the line after typing
    "beautify.onSave": true,

    "editor.formatOnSave": true,

    // You can auto format any files based on the file extensions type.
    "beautify.JSfiles": [
        "js",
        "json",
        "jsbeautifyrc",
        "jshintrc",
        "ts"
    ]
}

Note: now you can auto format TypeScript files. Check my update.

Solution 3

You can add a keybinding in menu FilePreferencesKeyboard shortcuts.

{ "key": "cmd+k cmd+d", "command": "editor.action.formatDocument" }

Or Visual Studio like:

{ "key": "ctrl+k ctrl+d", "command": "editor.action.formatDocument" }

Solution 4

  1. Right click somewhere in the content area (text) for the file
  2. Select Format Document from the menu:
    • Windows: Alt+Shift+F
    • Linux: Alt+Shift+I
    • macOS: ++F

Enter image description here

Solution 5

The right key combination is Shift + Alt + F.

Share:
3,324,677
Brandon Clapp
Author by

Brandon Clapp

Updated on May 05, 2022

Comments

  • Brandon Clapp
    Brandon Clapp about 2 years

    What is the equivalent of Ctrl + K + F and Ctrl + K + D on Windows in Visual Studio for formatting, or "beautifying" code in the Visual Studio Code editor?

    • informatik01
      informatik01 about 8 years
      For all those desperately trying to format XML (which seems not possible out of the box currently) you can achieve this by installing an extension. I have found XML Tools to get the job done just fine. Disclaimer: I am not the author nor related to this project...
    • Roland
      Roland over 7 years
      While VSCode has much fewer menu options than VS (new trend?), it has extensive info and tutorials under the HELP menu, which may have answered this question.
    • Mr.Hunt
      Mr.Hunt over 6 years
      For all those struggling to get the formatting work even after trying the valid combinations in Visual Studio Code, don't forget to select the appropriate programming language type, it is at the bottom right in visual studio code window next to that smiley. Once you do that I found it works out of the box and you don't need any additional plugin to format code.
  • Jens Ehrich
    Jens Ehrich almost 9 years
    In Windows, replace cmd with ctrl - don't just blindly copy and paste like I did!
  • Litera
    Litera over 8 years
    Also note that the code Language has to be correct. ie Format Code won't be available if plain text is selected but switching to JSON (for example) will format the selected text happily. (as happy as a text editor can be anyway)
  • Asheesh
    Asheesh over 8 years
    @JoSmo: On Ubuntu, I opened File > Preferences > Keyboard Shortcuts. There is an item for { "key": "ctrl+shift+i", "command": "editor.action.format", "when": "editorTextFocus" }. The command "ctrl+shift+i" works for me.
  • Jamie Carl
    Jamie Carl over 8 years
    I guess it depends on the language. CTRL + SHIFT + I works for JavaScript but not for PHP, for example.
  • Dinoel Vokiniv
    Dinoel Vokiniv about 8 years
    Also, apparently the file has to be saved to disk first. I had a chunk of HTML+Javascript where it couldn't format the JS, so I pasted it to a temporary window and set the language, but this didn't help either until it was saved.
  • equiman
    equiman almost 8 years
    Also works for another language with this: Beautify Extension
  • Chris Adams
    Chris Adams almost 8 years
    For the people saying it doesn't work on a Mac, this looks like a conflict between the shortcut and the OS X text input system for accented characters which depends on your configured locale and keyboard settings: github.com/Microsoft/vscode/issues/8914#issuecomment-2459478‌​44
  • Beauty
    Beauty over 7 years
    When you just copy&paste code from clipboard to a new tab, then nothing happens. Solution: Save the code to a file with a related file extension (e.g. *.json). Then it works. I suppose the reason is that the beautifyer knows the language from the extension and doesn't do an autodetect based on the code.
  • ESP32
    ESP32 over 7 years
    Sure, I am using Windows and it works as described - it might depend on VScode version (please update!) and on file extension. Please test with HTML.
  • Red Riding Hood
    Red Riding Hood over 7 years
    "editor.action.format" is working again. It now formats the whole document if nothing is selected, else formats the selection.
  • mrówa
    mrówa over 7 years
    In current version of VSCode (1.8.1) there's action in Command + P menu "Format document" and it's available also in context menu on file contents - but only for supported types of documents.
  • a11smiles
    a11smiles over 7 years
    not sure why it's different in CentOS, but it's Shift + Alt + I
  • Highmastdon
    Highmastdon about 7 years
  • Ben Petersen
    Ben Petersen about 7 years
    beautify.onSave is not valid with the eslint extention installed
  • Pini Cheyni
    Pini Cheyni almost 7 years
    On ubuntu mate 17.04 it Shift + Alt + I too
  • HendraWD
    HendraWD almost 7 years
    I am trying VSCode right now, it is very slow to format the codes in my project, around 6 seconds. I don't know what's wrong here. The file that i am trying to format is around 4k lines. If i am using PHPStorm IDE, the format happens instantly.
  • Jay
    Jay over 6 years
    This doesn't work for me on VS Code latest version and win 10 does this assume having a certain extension installed?
  • jordan.baucke
    jordan.baucke over 6 years
    link is dead- extension 404?
  • Oncel Umut TURER
    Oncel Umut TURER over 6 years
    In order to format C# one needs to install extensions. Normally omnisharp should work. However, there is a bug in omnisharp. Until the bug fixed we have to use Leopotam.csharpfixformat extension. It overrides omnisharp. After installing C# FixFormat extension I can format documents again.
  • SelvamSankarans
    SelvamSankarans over 6 years
    Useful for me as a beginner to VSCode. Command + P is not working in VS 1.19.3 on Mac OS X 10.13.3. But Command + Shift + P - Format Document is working fine. Also Shift + Opt + F works fine.
  • default_noob_network
    default_noob_network over 6 years
    oddly enough, i have found the behavior of this setting can be different than shift+alt+f in certain situations. don't know why though!
  • mmushtaq
    mmushtaq about 6 years
    Shift + Alt + F is messing up with '. After pressing this combination, the ' are changed to ", which is causing error in typescript.
  • Leandro
    Leandro about 6 years
    I suggest EsLint extension for VS Code marketplace.visualstudio.com/…
  • Enn
    Enn about 6 years
    @ClintEeastwood try using prettier.singleQuote: true in your vs code settings.
  • Haydar Ali Ismail
    Haydar Ali Ismail about 6 years
    for Mac should be Shift + Option + F
  • yairr
    yairr almost 6 years
    Oddly this feature appears to only function with explicit saves. In other words, auto save feature does not also trigger beautification.
  • Cees Timmerman
    Cees Timmerman over 5 years
    Beautify asks you if it doesn't know which formatter to use, allowing one to style cshtml.
  • DioBrando
    DioBrando over 5 years
    With this command,in my TypeScript files, single quote becomes double quote. How to solve that?
  • Oliver Dixon
    Oliver Dixon over 5 years
    Can't seem to locate this in the new settings garbage UI.
  • Daniel Jackson
    Daniel Jackson over 5 years
    When I have this enable and I create a function in C#, I can complete the whole thing and move on yet the function isn't formatted until I do the "Format Document" feature. I don't know why the above setting doesn't format after typing a function.
  • Tola Odejayi
    Tola Odejayi over 5 years
    Can't find 'Workplace Settings', just 'File' > 'Preferences' > 'Settings'.
  • Bharathi Devarasu
    Bharathi Devarasu over 5 years
    @TolaOdejayi If you are using Mac OS go to Code --> Preference --> Settings --> Workspace Settings ( Tab Navigation)
  • Peter Mortensen
    Peter Mortensen about 5 years
    Not this one what? Are you referring to another answer? If yes, which one?
  • C. Damoc
    C. Damoc about 5 years
    This shortcut works for MAC. In Windows it formats the code.
  • Lucas
    Lucas about 5 years
    For Linux the keyboard shortcuts are Ctlr + Shift + I
  • volvox
    volvox about 5 years
    Nope for me on 1.34.0 with a piece of hcl and the Terraform plugin installed. I love my vi.
  • Ondra Starenko
    Ondra Starenko about 5 years
    It used to work pretty well but now VSCode says "There is no formatter for 'plaintext'-files installed"
  • Andrew Fogg
    Andrew Fogg almost 5 years
    Note that VS Code will not allow you to format large files but instead of telling you that will just offer the generic message "no formatter installed"
  • Simon Hutchison
    Simon Hutchison almost 5 years
    If you want to change the default formatter you can do it like this: Open a file -> Right click on the code window -> Select Format Document With... -> Configure Default Formatter... -> Pick a new formatter.
  • rotgers
    rotgers almost 5 years
    Where do I put this? It also helps to add that beautify is an extension...
  • user3885927
    user3885927 almost 5 years
    Some times I copy paste xml into a new file and want to format it without saving the file. This is perfect for such situations!
  • birgersp
    birgersp over 4 years
    You could have mentioned where to put this code.
  • nonopolarity
    nonopolarity over 4 years
    I noticed when you bring out the command search, there are "Format Document" and "Reindent Lines" and "Format Document" reindent better (if in my source code, I commented out setTimeout(function() { and the }, 1000); a few lines below, then "Reindent Lines" treat this comment as really opening up a block scope, but then also did not close the commented out closing }
  • kmoser
    kmoser over 4 years
    Yeah, but only 2 out of 5 stars? Seriously?
  • mumair
    mumair over 4 years
    Just a reminder: this answer was originally written in 2017 and that time VS Code functionality was pretty much functional via plugins or other hacks, none of other solutions worked for me that time so I discover it by myself which actually worked that time and did not cared how many stars it have :-) Now 2020 and formatting support is fantastic out of the box.
  • kmoser
    kmoser over 4 years
    I don't think VS Code yet supports formatting CSS out of the box. I installed the Prettier plugin (prettier.io) which handles JavaScript, TypeScript, Flow, JSX, JSON, CSS, SCSS, Less, HTML, Vue, Angular, GraphQL, Markdown, YAML. 5.6 million installs and 4 stars.
  • mumair
    mumair over 4 years
    I am glad that you found prettier :P Formatting support is there but not good as prettier, I use prettier as dev-dependency in my all projects with .prettierrc and plugin. I am afraid that one day prettier will merge into vs-code :)
  • london_utku
    london_utku about 4 years
    For Mac, shift + option + F is search menu. This is not correct, at least for Mac.
  • Philip Rego
    Philip Rego about 4 years
    Does not work with JSON unless the file has a .json extension.
  • Peter Mortensen
    Peter Mortensen about 4 years
    Can you add something to your answer about the conditions under which this works? For instance, it does not work (nothing happens) by default for C# (.cs) - tried on Linux (Ubuntu MATE 20.04 with Visual Studio Code 1.41.1, 2020-05-14). Whereas it worked for an HTML (.html) file on the same system.
  • Peter Mortensen
    Peter Mortensen about 4 years
    Possible solution for C# in: Visual Studio Code doesn't format C# code
  • Peter Mortensen
    Peter Mortensen about 4 years
    But what is the consequence? How will it actually work after the change? Will it immediately / automatically change the formatting as something is typed? Also at paste?
  • Peter Mortensen
    Peter Mortensen about 4 years
    As this is the accepted answer to a locked question that is effectively a canonical question (many people looking for formatting C#, PHP, CSS, and other languages in Visual Studio Code will end up here), it deserves a more comprehensive answer.
  • Peter Mortensen
    Peter Mortensen about 4 years
    As this is the only answer that addresses the question many people looking for formatting C#, PHP, CSS, and other languages in Visual Studio Code have, it deserves more comprehensive content. (The question they have is: "Why doesn't this work???? All the answers here claim it does!")
  • Peter Mortensen
    Peter Mortensen about 4 years
    I think the content should be in this answer (as an answer to a (locked) canonical question), but a possible solution for C# is in Visual Studio Code doesn't format C# code
  • Roi Shabtai
    Roi Shabtai about 4 years
    @PeterMortensen Simply try it out and comment the answer
  • robalem
    robalem almost 4 years
    @gromit190 You should put it in the settings.json. Open the Command Palette (Windows: Ctrl+Shift+P. Mac: Cmd+Shift+P), and then enter 'Open Settings (JSON)'.
  • Ramil Aliyev
    Ramil Aliyev almost 4 years
    Excellent ! Thanks
  • Shaiju T
    Shaiju T almost 4 years
    I don't see Preference --> Settings --> Workspace Settings in Windows ?
  • Mark van der Dam
    Mark van der Dam almost 4 years
    @shaijut it is located at File --> Preference --> Settings and then under the search bar you see User then to the right it says Workspace
  • Timo
    Timo over 3 years
    Under help, there is keyboard shortcut reference which points to a website with the shortcuts including this one.
  • Hamza Khanzada
    Hamza Khanzada over 3 years
    Shortcut keys are different for different operating systems, For Linux its Ctrl + Shift + I
  • abyshukla
    abyshukla almost 3 years
    @DioBrando, you might want to check the TypeScript formatting extension you use.
  • amdg
    amdg almost 3 years
    Works! But before doing this, I changed the language to JSON from Plain Text using the status bar in the bottom right-hand corner.
  • BMW
    BMW almost 3 years
    Thanks, this is helpful when my default formater is linked to a wrong one. You will saw an extra option "Format document with ..."
  • staticvoid17
    staticvoid17 over 2 years
    On my M1 Mac, I don't see an alt key
  • Muhy
    Muhy over 2 years
    @BrandonClapp How can I apply a formatter to a file that is not necessarily meant for that formatter? I am learning how to program in Q# in VS Code, and when I press shift+alt+f and look to install a Q# formatter, there is none found. So, I installed Csharpier to try and format my Q# scripts like C# scripts, but I cannot get it to apply the formatting. Do you know how to do this?
  • Muhy
    Muhy over 2 years
    How can I apply a formatter to a file that is not necessarily meant for that formatter? I am learning how to program in Q# in VS Code, and when I press shift+alt+f and look to install a Q# formatter, there is none found. So, I installed Csharpier to try and format my Q# scripts like C# scripts, but I cannot get it to apply the formatting. Do you know how to do this?