visit
Many editors and IDEs support the EditorConfig file by default, and others . Here are some:
It has a default name of .editorconfig
and is an INI file where sections are filename filters, for instance:
[*.cs]
for .cs
files;[scripts/**.js]
for javascript files inside the scripts
folder and subdirectories;[{package.json}]
for the package.json
file only.
To include an EditorConfig to your project, just create a file named .editorconfig
in the same directory of your solution file (.sln
) with the content below.
# Top-most EditorConfig file.
root = true
# Section for C# files
# All rules below apply only to .cs files
[*.cs]
#### Core EditorConfig Options ####
# Indentation and spacing
indent_style = space
indent_size = 4
# New line preferences
end_of_line = crlf
insert_final_newline = false
trim_trailing_whitespace = true
# Charset preference
charset = utf-8
⚠️ GIT can change the line ends to LF on pushes to the repository and change it back to CRLF on checkouts. Then, the
end_of_line
settings can be safely set to CRLF. GIT for Windows suggests this configuration by default at installation. Details on how to configure are .
⚠️ UTF-8 with BOM is not required nor recommended, according to the Unicode standard. .
ℹ️ In .NET, the EditorConfig file can also be used to define analyzers rules and severities specific to the .NET environment. In a next post, I'll show how to configure these rules.
First, we have to include the Format document
fixer to a Code Cleanup profile.
1 - Navigate to Analyze > Code Cleanup > Configure Code Cleanup
.
2 - Include the Format document
fixer for the profile you wish to run on save.
3 - On the menu, select Analyze > Code Cleanup > Run Code Cleanup (Yout Profile) on Solution
.
⚠️ Visual Studio's format document doesn't change the file encoding. You have to use the dotnet-format or another tool for that.
2 - Navigate to View > Command Palette
or press Ctrl+Shift+P
.
3 - Select the Start Format Files: Workspace
or Start Format Files: From Glob
option.
Select Code > Reformat Code
or press Ctrl+Alt+Enter
.
Visual Studio 2022 doesn't have a format on save feature, but it can run a Code Cleanup on save. This way we can configure a Code Cleanup profile to run a Format document
and use it on save.
ℹ️ For Visual Studio 2019, there is an that enables the same feature.
1 - Configure your Code Cleanup profile to run the Format document
fixer, as shown in the previous section of this post.
2 - Navigate to Tools > Options > Text Editor > Code Cleanup
.
3 - Check the Run Code Cleanup profile on Save
option and select the Code Cleanup profile to run on save.
1 - Navigate to File > Preferences > Settings
.
2 - Navigate to Text Editor > Formatting
or search for editor.formatOnSave
.
3 - Check the Editor: Format On Save
option.
1 - Navigate to File > Settings > Tools > Actions on Save
.
2 - Check the Reformat and Cleanup Code
option.
3 - Select the Reformat Code
profile.