How do you format code in Visual Studio Code (VSCode)?
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
-
Open command palette (Win: F1 or Ctrl+Shift+P)
-
Find "Change Language Mode"
-
Select language e.g.
json
. By now syntax should be highlighted. -
Format document (e.g. Open Command Palette -> "Format Document")
Unformat
- Select text
- Command Palette -> Join Lines
'Show the pics'
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 File → Preferences → Workspace 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 File → Preferences → Keyboard 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
- Right click somewhere in the content area (text) for the file
- Select Format Document from the menu:
- Windows: Alt+Shift+F
- Linux: Alt+Shift+I
- macOS: ⌥+⇧+F
Solution 5
The right key combination is Shift + Alt + F.
Brandon Clapp
Updated on May 05, 2022Comments
-
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 about 8 yearsFor 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 over 7 yearsWhile 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 over 6 yearsFor 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 almost 9 yearsIn Windows, replace
cmd
withctrl
- don't just blindly copy and paste like I did! -
Litera over 8 yearsAlso 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 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 over 8 yearsI guess it depends on the language.
CTRL + SHIFT + I
works for JavaScript but not for PHP, for example. -
Dinoel Vokiniv about 8 yearsAlso, 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 almost 8 yearsAlso works for another language with this: Beautify Extension
-
Chris Adams almost 8 yearsFor 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-245947844
-
Beauty over 7 yearsWhen 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 over 7 yearsSure, 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 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 over 7 yearsIn 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 over 7 yearsnot sure why it's different in CentOS, but it's
Shift + Alt + I
-
Highmastdon about 7 yearsThis is the extension: marketplace.visualstudio.com/items?itemName=HookyQR.beautify
-
Ben Petersen about 7 yearsbeautify.onSave is not valid with the eslint extention installed
-
Pini Cheyni almost 7 yearsOn ubuntu mate 17.04 it
Shift + Alt + I
too -
HendraWD almost 7 yearsI 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 over 6 yearsThis doesn't work for me on VS Code latest version and win 10 does this assume having a certain extension installed?
-
jordan.baucke over 6 yearslink is dead- extension 404?
-
Oncel Umut TURER over 6 yearsIn 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 over 6 yearsUseful 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 over 6 yearsoddly 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 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 about 6 yearsI suggest EsLint extension for VS Code marketplace.visualstudio.com/…
-
Enn about 6 years@ClintEeastwood try using
prettier.singleQuote: true
in your vs code settings. -
Haydar Ali Ismail about 6 yearsfor Mac should be
Shift + Option + F
-
yairr almost 6 yearsOddly this feature appears to only function with explicit saves. In other words, auto save feature does not also trigger beautification.
-
Cees Timmerman over 5 yearsBeautify asks you if it doesn't know which formatter to use, allowing one to style cshtml.
-
DioBrando over 5 yearsWith this command,in my TypeScript files, single quote becomes double quote. How to solve that?
-
Oliver Dixon over 5 yearsCan't seem to locate this in the new settings garbage UI.
-
Daniel Jackson over 5 yearsWhen 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 over 5 yearsCan't find 'Workplace Settings', just 'File' > 'Preferences' > 'Settings'.
-
Bharathi Devarasu over 5 years@TolaOdejayi If you are using Mac OS go to Code --> Preference --> Settings --> Workspace Settings ( Tab Navigation)
-
Peter Mortensen about 5 yearsNot this one what? Are you referring to another answer? If yes, which one?
-
C. Damoc about 5 yearsThis shortcut works for MAC. In Windows it formats the code.
-
Lucas about 5 yearsFor Linux the keyboard shortcuts are Ctlr + Shift + I
-
volvox about 5 yearsNope for me on 1.34.0 with a piece of hcl and the Terraform plugin installed. I love my vi.
-
Ondra Starenko about 5 yearsIt used to work pretty well but now VSCode says "There is no formatter for 'plaintext'-files installed"
-
Andrew Fogg almost 5 yearsNote 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 almost 5 yearsIf 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 almost 5 yearsWhere do I put this? It also helps to add that beautify is an extension...
-
user3885927 almost 5 yearsSome 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 over 4 yearsYou could have mentioned where to put this code.
-
nonopolarity over 4 yearsI 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 over 4 yearsYeah, but only 2 out of 5 stars? Seriously?
-
mumair over 4 yearsJust 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 over 4 yearsI 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 over 4 yearsI 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 about 4 yearsFor Mac, shift + option + F is search menu. This is not correct, at least for Mac.
-
Philip Rego about 4 yearsDoes not work with JSON unless the file has a
.json
extension. -
Peter Mortensen about 4 yearsCan 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 about 4 yearsPossible solution for C# in: Visual Studio Code doesn't format C# code
-
Peter Mortensen about 4 yearsBut 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 about 4 yearsAs 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 about 4 yearsAs 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 about 4 yearsI 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 about 4 years@PeterMortensen Simply try it out and comment the answer
-
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 almost 4 yearsExcellent ! Thanks
-
Shaiju T almost 4 yearsI don't see
Preference --> Settings --> Workspace Settings
in Windows ? -
Mark van der Dam almost 4 years@shaijut it is located at
File --> Preference --> Settings
and then under the search bar you seeUser
then to the right it saysWorkspace
-
Timo over 3 yearsUnder help, there is keyboard shortcut reference which points to a website with the shortcuts including this one.
-
Hamza Khanzada over 3 yearsShortcut keys are different for different operating systems, For Linux its
Ctrl
+Shift
+I
-
abyshukla almost 3 years@DioBrando, you might want to check the TypeScript formatting extension you use.
-
amdg almost 3 yearsWorks! But before doing this, I changed the language to
JSON
fromPlain Text
using the status bar in the bottom right-hand corner. -
BMW almost 3 yearsThanks, this is helpful when my default formater is linked to a wrong one. You will saw an extra option "Format document with ..."
-
staticvoid17 over 2 yearsOn my M1 Mac, I don't see an
alt
key -
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 pressshift+alt+f
and look to install aQ#
formatter, there is none found. So, I installedCsharpier
to try and format myQ#
scripts likeC#
scripts, but I cannot get it to apply the formatting. Do you know how to do this? -
Muhy over 2 yearsHow 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 pressshift+alt+f
and look to install aQ#
formatter, there is none found. So, I installedCsharpier
to try and format myQ#
scripts likeC#
scripts, but I cannot get it to apply the formatting. Do you know how to do this?