I have enabled the latest C# extension in my Visual Studio Code editor. Instead of formatting the code while saving or by applying the key combination Ctrl + K, Ctrl + F or Alt + Shift + F, I need to format the current line of code while hitting the Enter key. This feature is already available in Visual Studio, but not found in Visual Studio Code by default.
This is the sample code output I need to achieve:
Go to menu File → Preference → Settings.
Search for format
Select the options you would like:
Format on Paste
Format on Save
Format on Type
Close the Settings window.
You can also see it in your settings.json file:
I have found an option which makes it easier to format code while typing.
I applied the below settings in workspace settings:
{
"editor.formatOnSave": true,
"editor.formatOnType": true
}
This works fine for me.
Go to menu File → Preferences → Keyboard Shortcut (Ctrl + K, Ctrl + S)
Click on the keybindings.json
link:
Enter the below binding for the Enter key. This binding will overwrite the defaults for current user.
{
"key": "enter",
"command": "editor.action.formatDocument",
"when": "editorHasSelection"
}
Another alternative solution is to use macros extension - a custom macros support for Visual Studio Code, so you will be able to do more than one command in one key binding.
Add macros to User Settings
:
"macros": {
"formatWithEnter": [
"editor.action.insertLineAfter",
"editor.action.formatDocument"
]
}
And the below key binding to keybindings.json
:
{
"key": "enter",
"command": "macros.formatWithEnter"
}
Code formatters available on Visual Studio default as
If you again wish to do it when pressing Enter you need to set up your workspace preferences and then configure the key bindings:
{ "key": "enter", "command": "editor.action.format" }
It now formats the whole document if nothing is selected, and else it formats the selection.
Also there is the beautify.onSave, editor.formatOnSave option. Please try that too to make the code pretty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With