ReSharper 2021.1 Help

Manage and Apply Code Formatting Rules

ReSharper | Edit | Reformat Code
Control+Alt+L
ReSharper_ReformatCode

An important aspect of code style is how to format the code, that is, how to use whitespaces, tabs, and line breaks to arrange code elements, whether and how to use tabs for indents, whether and how to wrap long lines, and so on.

The extensive set of ReSharper code formatting rules has a default configuration that takes into account default Visual Studio formatting options as well as numerous best practices. You can configure every detail of formatting rules and enforce the rules in your code. These rules are applied when ReSharper produces new code with code completion and code generation features, applies code templates and performs refactorings. The formatting rules can also be applied to the existing code in the current selection, current file, or in a larger scope up to the entire solution.

Auto-format edited and pasted code

When you type code in the editor, ReSharper reformats expressions as soon as you type a semicolon ; and reformats blocks of code as soon as you type a closing brace }. If necessary, you can disable these kinds of auto-formatting on the Environment | Editor | Behavior page of ReSharper options(Alt+R, O).

ReSharper also lets you automatically apply your formatting rules when you paste code. By default, pasted code is not fully reformatted but only indentation settings are applied. If you want to fully format pasted code, or disable formatting on paste, use the Auto-format on paste selector on the Environment | Editor | Behavior page of ReSharper options(Alt+R, O).

Note that by default, Visual Studio applies its own formatting rules for edited and pasted code. If you are using ReSharper auto-formatting features, we recommend that you disable Visual Studio auto-formatting. You can do it in Visual Studio options (Tools | Options). For C# for example, clear the corresponding check-boxes on the Text Editor | C# | Code Style | Formatting | General options page.

Reformat existing code

ReSharper provides several ways to reformat existing code. In short, you can always use Control+Alt+L, but there are a few details and alternatives described below.

Reformat existing code in any scope

  1. Select the scope where you want to reformat code:

    • Make a selection in the editor to reformat code in the selection.

    • Set the caret anywhere in the file to reformat code in the file.

    • Select one or more items in the Solution Explorer to reformat code in files under these items and their child items.

  2. Press Control+Alt+L or choose ReSharper | Edit | Reformat Code from the main menu. Alternatively, you can press Control+Shift+A, start typing the command name in the popup, and then choose it there.

You can reformat code in the current selection right from the Alt+Enter action list.

Reformat code in the current selection

  1. In the editor, select a block of code that you want to reformat.

  2. Press Alt+Enter or click the action indicator to the left of the caret to open the action list.

  3. Select Themed icon code cleanup option page screen gray Format selection in the action list.

    Reformatting currently selected code

Alternatively, you can use code cleanup to reformat code in any scope. Code cleanup may be helpful if you want to combine code reformatting with applying other code styles.

Reformat code with Code Cleanup

  1. Select the scope where you want to reformat code:

    • Make a selection in the editor to reformat code in the selection.

    • Set the caret anywhere in the file to reformat code in the file.

    • Select one or more items in the Solution Explorer to reformat code in files under these items and their child items.

  2. Do one of the following:

    • Press Control+Alt+F or choose ReSharper | Edit | Cleanup Code... from the main menu.

    • Right-click anywhere in the text editor or right-click the selection and choose Cleanup Code in the context menu.

  3. In the Code Cleanup dialog that opens, select the Built-in: Reformat Code profile.

  4. Click Run. ReSharper will reformat code in the selected scope according to your formatting preferences.

If you want to reformat code without opening the Code Cleanup dialog to choose a profile, you can bind the default Reformat Code profile to the silent cleanup and run it by pressing Control+Shift+Alt+F. You can also create a custom cleanup profile that would combine code reformatting with other code style tasks.

Use code inspection to maintain formatting rules in C# and C++

In C# and C++, code formatting style can be also maintained using the code inspection features. ReSharper provides several dozens of formatting inspections, which are all disabled by default.

Depending on the solution, your codebase may have hundreds of minor formatting violations, like different indent sizes across methods, different case-label indents in switch-statements, missing line breaks, and so on. Enabling code inspections for all those violations could be too noisy.

On the other hand, there are formatting problems that decrease code readability or may influence your understanding of the code. For example:

  • multiple type members on one same line,

  • multiple statements on one line,

  • incorrect indent around child statement,

  • incorrect indent around declaration braces.

For such formatting problems, we recommend enabling code inspections.

ReSharper: Code inspections and quick-fixes for violations of the code formatting style

Keep existing formatting

You can apply some formatting rules 'softly', meaning that such rules will be applied when ReSharper produces new code with code completion and code generation features, applies code templates and performs refactorings, but these rules will be ignored when you reformat existing code (for example, with Control+Alt+L).

To keep formatting rules less strict, use the Keep existing..., Keep max blank lines, and Simple wrap preferences for specific contexts. You can check or change the configuration of those preferences in ReSharper options(Alt+R, O):

ReSharper: keep existing formatting for selected rules

Reformat code with different line-break styles

ReSharper also allows you to use explicit actions rather than formatting rules to reformat similar code in different ways. These actions are most helpful when you opt to keep existing formatting for the related rules. However if you have stricter settings, then the corresponding explicit formatting actions will not work because such configurations mean that formatting rules should be always applied in the affected contexts. For example, if Keep existing... preferences are disabled, then the wrap/chop/spacious/compact commands described below will render the same result. If some wrapping rules are set to Chop..., code in the corresponding contexts will be always chopped even if you invoke wrap/compact commands.

Wrap and chop long lines

The Wrap long line and Chop long line actions become available when your caret is on a line, which is longer than the allowed maximum line length — you can configure it with the Right margin (columns) preference on the Code Editing | C# | Formatting Style | Line Breaks and Wrapping page of ReSharper options(Alt+R, O).

You can press Alt+Enter and choose one of the actions to add the necessary line breaks.

The Wrap long line will add just enough line breaks to make sure that the configured line length is not exceeded:

Before reformatting

var reportHtml = CreateReport("359CD313-7C7E-49B2-A2AB-E12FDFD1319D", DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow, useRichText: true);

After reformatting

var reportHtml = CreateReport("359CD313-7C7E-49B2-A2AB-E12FDFD1319D", DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow, useRichText: true);

The Chop long line will add line breaks for each entity on the line:

Before reformatting

var reportHtml = CreateReport("359CD313-7C7E-49B2-A2AB-E12FDFD1319D", DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow, useRichText: true);

After reformatting

var reportHtml = CreateReport("359CD313-7C7E-49B2-A2AB-E12FDFD1319D", DateTimeOffset.UtcNow.AddMonths(-1), DateTimeOffset.UtcNow, useRichText: true);

Compact, spacious, and strict format for code blocks

Another set of actions for explicitly reformatting your code helps you enforce more compact (fewer line breaks) or more spacious (more line breaks) format in the selection.

To invoke these actions, select a block of code (you can use Control+W to select a logical block), press Alt+Enter and then choose one of the actions under Format selection.

If you have too many line breaks, which do not help reading the code, it may be a good idea to remove them. In the example below, the empty getters and setters do not bring any useful information and can be safely placed on single lines. You can do this with the Compact format (fewer line breaks) action:

Before reformattingAfter reformatting
public string Name { get; set; } public int Age { get; set; }
public string Name { get; set; } public int Age { get; set; }

You may want to use Spacious format (chop) to make a multi-line code block even easier to read. For example, you may want to add more line breaks in a complicated if statement or a heavy XElement constructor call:

Before reformatting

summaryTable.Add(new XElement("tr", new XElement("td", XmlHelpers.CreateHyperlink(inspection.Text, CodeInspectionHelpers.TryGetStaticHref(inspection.Id), null, true), new XComment(compoundName)), new XElement("td", GetSeverityLink(inspection.Severity))));

After reformatting

summaryTable.Add(new XElement("tr", new XElement("td", XmlHelpers.CreateHyperlink(inspection.Text, CodeInspectionHelpers.TryGetStaticHref(inspection.Id), null, true), new XComment(compoundName)), new XElement("td", GetSeverityLink(inspection.Severity))));

The Strict format action will reformat the selection ignoring any existing line breaks independently of how the Keep existing... preferences are configured.

Configure code-formatting rules

Formatting rules can be configured to a very high level of detail. For example, you can define whether whitespaces should be placed around a specific operator or whether to indent nested using statements.

Configure code-formatting rules

  1. Select ReSharper | Options from the main menu or press Alt+R O.

  2. Use the Code Editing | General Formatting Style page to check and to configure the options that apply in all languages.

  3. Use the Code Editing | [Language] | Formatting Style pages to configure language-specific formatting preferences. On these pages, you can use the preview area at the bottom to view just how ReSharper applies the specific preference to the code.

  4. Click Save in the Options dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using the Save To list. For more information, see Manage and Share ReSharper Settings.

As an alternative to digging through options pages, you can select a block of code and configure only those formatting rules that are applicable to that block. You will be able to observe how modified formatter settings affect code in the selected block right in the editor.

Configure formatting rules for selected code

  1. In the editor, select a block of code that you want to reformat.

  2. Press Alt+Enter or click the action indicator to the left of the caret to open the action list.

  3. Choose Format selection | Configure.

  4. In the dialog that opens, you will see all formatting rules that affect the selected code block. The code block itself will be surrounded with a dotted frame:

    Configuring formatting rules for selected code
  5. As you change the formatting rules, you will see how they affect the code in the selected block.

  6. Click Save in the dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using the Save To list. For more information, see Manage and Share ReSharper Settings.

  7. Note that you can also choose to export the configured formatting rules to EditorConfig by choosing .editorconfig in the Save To selector.

  8. Optionally, you can click Save As Comments. This way your modifications will be saved as comments before and after the selected block. This lets you override desired formatter rules locally without modifying any settings.

  9. ReSharper will close the dialog and reformat the code block.

Use formatting rules from existing code

Another alternative to tweaking individual formatting preferences is to learn formatting rules from an existing code sample, which can be a selected block, the current file, a set of files, one or more projects, or the entire solution. ReSharper will analyze the selected sample and list formatting rules that differ from your current settings. You will then be able to review the detected rules, change them as required, and save them to the desired settings layer or to a configuration file in the .editorconfig or .clang-format format.

Learn formatting rules from existing code

  1. Select the scope where you want to analyze formatting:

    • Make a selection in the editor to analyze formatting in the selection.

    • Set the caret anywhere in the file to analyze formatting in the file.

    • Select one or more items in the Solution Explorer to analyze formatting in files under these items and their child items.

  2. Do one of the following:

    • Choose ReSharper | Edit | Detect Formatting Settings in the main menu.

    • Right-click and choose Detect Formatting Settings in the context menu.

    • If the code sample is a selection, press Alt+Enter and choose Format selection | Detect formatting settings.

  3. Review the rules that differ from your current settings:

    ReSharper: Using formatting rules from existing code

  4. Click Save in the dialog to apply the modifications and let ReSharper choose where to save them, or save the modifications to a specific settings layer using the Save To list. For more information, see Manage and Share ReSharper Settings.

  5. If the code sample is a selection, you can optionally click Save As Comments. This way your modifications will be saved as comments before and after the selected block. This lets you override desired formatter rules locally without modifying any settings.

Use comments to configure formatter

ReSharper allows you to deviate from the configured formatting rules without actually changing the rules. You can even disable formatter altogether in certain parts of your code.

You can configure formatter with comments in C#, C++, JavaScript, TypeScript, HTML, and Protobuf.

To disable formatter, use the following comments:

  • // @formatter:off — disable formatter after this line

  • // @formatter:on — enable formatter after this line

If disabling formatter is too much, you can change any individual formatting rule with a comment.

Change an individual formatting rule with a comment

  1. Find the name of formatting rule that you want to tweak. You can look it up on the Code Editing | [Language] | Formatting Style page of ReSharper options(Alt+R, O) or alternatively, you can select a code block where the desired rule applies, press Alt+Enter, and choose Format selection | Configure. In the dialog that opens you can study all rules that affect the selection and even change them to see a live preview of the change. In this dialog, you can also click Save as comments and ReSharper will generate the necessary comments for all modified rules..

  2. When you know the name of the rule, you can look up its ID in the Index of EditorConfig properties — use search in your browser. For example, if you want to find the rule that triggers the space before the semicolon, search for before semicolon and you will find the ID: space_before_semicolon.

  3. When you found the ID of the rule on the index web page, click the description link to learn which values are allowed for this rule. Following the example with space_before_semicolon, it can accept true or false.

  4. Add the following comment before the code where you want to change the rule:
    // @formatter:<rule_ID> <value>, for example, to enable spaces before the semicolon, add
    // @formatter:space_before_semicolon true.

  5. The new value for the rule will apply until the end of the file. If you want to go back to the value configured in the options, add the following comment:
    // @formatter:<rule_ID> restore, for example,
    // @formatter:space_before_semicolon restore.

Store and share formatting rules

Your code formatting preferences are saved using the mechanism of layer-based settings. Among other things, this mechanism allows you to maintain different preferences for different solutions as well as to keep these preferences under a VCS and automatically share them with your team members.

You can also configure formatting settings via in EditorConfig for all languages and Clang-Format for C++, JavaScript, and TypeScript. These settings can be stored in .editorconfig, .clang-format, or _clang-format files on different levels of your solution hierarchy. The files are normally put under VCS so that settings defined there are shared among the project team.
ReSharper lets you use EditorConfig to define any of its formatting preferences that are available in the ReSharper's Options dialog. You can find names and descriptions of supported EditorConfig properties in the EditorConfig reference.
As for Clang-Format, ReSharper will only apply the supported Clang-Format options.

It is important to note that any formatting property defined in an .editorconfig file will override the same property defined in ReSharper settings in the scope where this .editorconfig file applies. Formatting properties defined in Clang-Format will override both ReSharper settings and EditorConfig settings.

Another important thing to know when sharing formatting options is that indent style (tabs/spaces) and size are by default taken from Visual Studio options. If you want to share these preferences for specific language, clear the Use indent style and size from Visual Studio checkbox on the Code Editing | [Language] | Formatting Style | Tabs and Indents page of ReSharper options and save the change to a shared settings layer.

This feature is supported in the following languages and technologies:

Language: C#Language: VB.NETLanguage: C++Language: HTMLLanguage: ASP.NETLanguage: RazorLanguage: JavaScriptLanguage: TypeScriptLanguage: CSSLanguage: XMLLanguage: XAMLLanguage: ResxLanguage: Build ScriptsLanguage: ProtobufLanguage: JSON
Feature is available in C#Feature is available in Visual Basic .NETFeature is available in C++Feature is available in HTMLFeature is available in ASP.NETFeature is available in RazorFeature is available in JavaScriptFeature is available in TypeScriptFeature is available in CSSFeature is available in XMLFeature is available in XAMLFeature is available in Resource filesFeature is available in build script filesFeature is available in ProtobufFeature is available in JSON

The instructions and examples given here address the use of the feature in C#. For details specific to other languages, see corresponding topics in the ReSharper by Language section.

Last modified: 22 June 2021