Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto format C# code In Visual Studio Code

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:

Enter image description here

like image 287
Joseph Jojo John Avatar asked Mar 26 '18 20:03

Joseph Jojo John


4 Answers

Go to menu FilePreferenceSettings.

Search for format

Select the options you would like:

  • Format on Paste

  • Format on Save

  • Format on Type

Close the Settings window.

Enter image description here

You can also see it in your settings.json file:

Enter image description here

like image 53
live-love Avatar answered Nov 20 '22 02:11

live-love


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.

like image 41
Joseph Jojo John Avatar answered Nov 20 '22 04:11

Joseph Jojo John


Go to menu FilePreferencesKeyboard Shortcut (Ctrl + K, Ctrl + S)

Click on the keybindings.json link:

Enter image description here

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"
}
like image 8
ElasticCode Avatar answered Nov 20 '22 03:11

ElasticCode


Code formatters available on Visual Studio default as

  • On Windows: Shift + Alt + F
  • On Mac: Shift + Option + F

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.

like image 2
errakeshpd Avatar answered Nov 20 '22 03:11

errakeshpd