Skip to content

Instantly share code, notes, and snippets.

@neogeek
Created February 14, 2022 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save neogeek/b4e4212fed7d0ad1c284b65207784f5e to your computer and use it in GitHub Desktop.
Save neogeek/b4e4212fed7d0ad1c284b65207784f5e to your computer and use it in GitHub Desktop.
Automatic Code Formatting in Rider

Automatic Code Formatting in Rider

.editorconfig

For this to work correctly across multiple computers and developers, each repo must have an .editorconfig file that determines what the code looks like when formatted. For an example, see the repo linked below.

https://github.com/neogeek/csharp_editorconfig

Context Menu Commands

Rider has reformatting built into the editor's context menu without any additional setup. Select a block of code, or the entire file, and press ALT + Enter (or Option + Enter for macOS developers). This will open the context menu. The first three options will pertain to formatting code: "Format selection", "Apply syntax style", and "Cleanup selection".

Key Commands

The key command we will be focusing on for this tutorial is "Reformat Code" found in the "Code" menu. This runs all formatting options on your code. The key command for this is Ctrl + Alt + L (or Option + Command + L for macOS developers).

Automatic Formatting

For ease of use, we are going to bind the "Reformat Code" to a macro that will also save the file.

  1. First, open the "Edit" menu, then "Macros" (at the bottom of the list), then "Start Macro Recording".
  2. Then without doing anything else, press the key commands for "Reformat Code" which is Ctrl + Alt + L (or Option + Command + L for macOS developers), and then "Save All" which is Ctrl + S (or Command + S for macOS developers).
  3. Then navigate back to the "Edit" then "Macros" menu and press "Stop Macro Recording".
  4. Give the macro a name like "Reformat Code + Save All".
  5. Then open the application preferences and then navigate to the "Keymap" section.
  6. Search for "Reformat Code + Save All".
  7. Right-click on the macro and hit "Add Keyboard Shortcut".
  8. Press Ctrl + S (or Command + S for macOS developers).
  9. When the dialog appears asking you if you want to remove all other commands with that keyboard shortcut, say yes.
  10. Hit "Save".

Now, the code will reformat to look the same for everyone whenever you save. This helps prevent unnecessary whitespace changes from developer to developer, keeping PRs smaller and focused on the actual changes.

:shipit:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment