RazorFmt.Cli 0.7.0

dotnet tool install --global RazorFmt.Cli --version 0.7.0
                    
This package contains a .NET tool you can call from the shell/command line.
dotnet new tool-manifest
                    
if you are setting up this repo
dotnet tool install --local RazorFmt.Cli --version 0.7.0
                    
This package contains a .NET tool you can call from the shell/command line.
#tool dotnet:?package=RazorFmt.Cli&version=0.7.0
                    
nuke :add-package RazorFmt.Cli --version 0.7.0
                    

RazorFmt

RazorFmt is a standalone, deterministic formatter for .razor and .cshtml files. It re-indents Razor markup and formats C# with Roslyn: @code / @functions bodies, pure-C# @{ ... } blocks, control-flow headers, common directive payloads, and single-line @( ... ) expressions.

It needs no project, IDE, MSBuild workspace, or server. Give it a file or a stream of text, and it returns formatted text or a diagnostic.

RazorFmt is pre-1.0. Review the syntax support and known limitations before running --write across a project.

Install

RazorFmt is a .NET tool and requires the .NET 10 runtime.

dotnet tool install --global RazorFmt.Cli
razorfmt --version

Update an existing installation:

dotnet tool update --global RazorFmt.Cli

Quick start

# Print one formatted file to stdout.
razorfmt Pages/Index.razor

# Preview changes without writing anything.
razorfmt --diff .

# CI check: exit 1 if any file would change.
razorfmt --check .

# Rewrite files in place.
razorfmt --write .

Directories are scanned recursively for .razor and .cshtml files. A file is only rewritten when formatting succeeds. Malformed or unsupported input is reported and left unchanged.

Read from stdin and write to stdout when no path is given:

Get-Content -Raw Pages/Index.razor | razorfmt
cat Pages/Index.razor | razorfmt --diff

Usage

razorfmt [options] [file-or-directory ...]
Option Meaning
-w, --write Rewrite changed files in place.
-c, --check Exit 1 if a file would change; write nothing.
-d, --diff Print a unified diff; write nothing.
--indent-size <N> Spaces per indent level (default 4).
--tabs Indent with tabs instead of spaces.
--no-csharp Do not run Roslyn over @code / @functions bodies.
--keep-blanks Do not collapse runs of blank lines.
--split-tags Put adjacent tags and inline Razor blocks on separate lines.
--no-split-tags Disable razorfmt_split_tags from .editorconfig.
--wrap-attributes Put each attribute of a long tag on its own line.
--no-wrap-attributes Disable razorfmt_wrap_attributes from .editorconfig.
--max-line-length <N> Tag wrapping threshold (default 120).
--split-code Reflow one-line C# statements and methods.
--no-split-code Disable razorfmt_split_code from .editorconfig.
-h, --help Show help.
--version Show the version.

--write, --check, and --diff are mutually exclusive. A directory or multiple paths require one of them; a single file without one of them is printed to stdout. With no path, stdin is formatted to stdout, and --check / --diff apply to that stream.

Options can appear before or after paths. Unknown options and missing values exit with code 2.

What each mode does

  • --write writes a sibling temporary file, flushes it, then moves it over the original. Windows uses File.Replace with a rename fallback; Unix preserves the original file mode.
  • --check prints would reformat <file> for each changed file and exits 1. On stdin it prints nothing and exits 1 when the input would change.
  • --diff prints a unified diff with --- / +++ headers and exits 1 when anything differs. Nothing is written.

Configuration

For file arguments, RazorFmt reads .editorconfig from the file's directory upward and stops at root = true. Stdin uses defaults.

Key Values Default
indent_style space, tab space
indent_size positive integer, or tab 4
tab_width positive integer indent_size
end_of_line lf, crlf, cr detected from the file
max_line_length positive integer, or off 120
razorfmt_split_tags true, false false
razorfmt_wrap_attributes true, false false
razorfmt_split_code true, false false

Command-line flags override .editorconfig. The --no-* variants turn a setting off for one run. --indent-size and --tabs take precedence over the matching editorconfig keys.

.editorconfig sections support *, ?, and ** globs. Extended globs such as brace expansion and character classes are not supported.

Directory scans skip bin, obj, .git, .vs, .idea, and node_modules, do not follow symlink or junction directories, and ignore generated names ending in .g.razor, .g.cshtml, .generated.razor, or .generated.cshtml. Explicit file paths must be .razor or .cshtml.

Example

root = true

[*.razor]
indent_style = space
indent_size = 2
end_of_line = lf
max_line_length = 100
razorfmt_wrap_attributes = true

Syntax support

RazorFmt formats structure and whitespace only. It does not change non-whitespace content.

Formatted

Construct Behaviour
Markup elements Nested content is indented. Void elements, self-closing tags, and multi-line tags are recognized.
Optional HTML end tags li, p, dt / dd, option, optgroup, tr, td / th, thead / tbody / tfoot, colgroup, and rt / rp are closed conservatively for indentation.
Razor control-flow headers The condition in @if, else if, @foreach, @await foreach, @for, @while, @switch, @using (...), @lock, @catch, and catch is formatted by Roslyn. @else, @try, and @finally are tracked as block openers.
@code / @functions The block body is formatted by Roslyn, including @<tag> ... </tag> template markup.
Razor templates Template markup inside @code is formatted and reinserted at the placeholder's indentation.
Pure-C# @{ ... } Formatted by Roslyn when the whole body parses as C#.
@( ... ) Formatted by Roslyn when the expression closes on the same line.
Directives @attribute, @implements, @inherits, and @typeparam payloads are parsed in a synthetic C# context and formatted.
Multi-line tags and headers Indented consistently. Short headers that fit in 100 columns are joined.
Comments HTML comments and @* ... *@ Razor comments are preserved.
@: literal text Treated as literal text and indented with its containing block.
<text> Recognized as a Razor pseudo-element.

Preserved as written

Construct Behaviour
<pre>, <textarea>, <script>, <style> Content is emitted verbatim, including indentation and line endings.
Multi-line strings and chars Content inside C# string and character literals is never reflowed.
Escaped @@( Left untouched.
Multi-line @( ... ) Left untouched; only same-line expressions are formatted.
Blocks mixing templates with direct markup lambdas Preserved when the remaining body cannot be parsed as C#.
Nested or unclosed templates Preserved; unclear boundaries are reported as RF027 and the file is left unchanged.
Attribute values Quoted component values such as Value="a+b" are string literals, not C#, and are not reformatted.
Mixed Razor/markup @{ ... } The block is indented but not C#-formatted. A single-line inline @{ <p>x</p> } is rejected instead.

Encoding and line endings

Files keep their original UTF-8 (with or without BOM), UTF-16, or UTF-32 encoding and their existing line endings. .editorconfig end_of_line overrides the detected style. Input that is not valid text, or that contains a NUL character, is refused rather than transcoded.

Exit codes

Code Meaning
0 Success, or no differences under --check / --diff.
1 Formatting differences under --check or --diff.
2 Usage or configuration error.
3 Parser or formatter failure.

When several files are processed, the highest applicable code wins, so a parser failure (3) is not hidden by a formatting difference (1).

Troubleshooting

razorfmt: <file>: RF0xx: ... and nothing changed. The formatter refused the file. Fix the reported syntax, or leave the construct as written. Exit code is 3. See the diagnostic table below.

RF027. A @code block contains a @<...> template whose closing tag could not be found, or the template boundaries overlap. Nothing was changed.

would reformat <file>. The file is valid but not formatted. Run razorfmt --diff <file> to review, then --write when the changes are safe.

--write and --check cannot be combined. Pick one mode. Use --diff as a read-only preview.

The file lost indentation in <pre> / <textarea>. It should not; raw element content is copied verbatim. Please report the file with a minimal reproduction.

--split-tags added spaces between inline elements. Splitting tags can introduce whitespace in rendered HTML, so the option is off by default. Use it only when whitespace between those elements is insignificant.

--split-code compacted a multi-line expression. It uses Roslyn's normalized layout, which can choose a shorter shape than the original. Leave the option off for hand-aligned expressions.

Attribute continuation lines were re-aligned. RazorFmt normalizes them to one indent level instead of preserving manual alignment.

Stdin ignored my .editorconfig. Stdin has no file path, so it uses defaults. Pass a file path, or set the options on the command line. The VS Code extension also uses stdin and therefore exposes the options as settings.

A generated file was skipped or rejected. Directory scans ignore names ending in .g.razor, .g.cshtml, .generated.razor, or .generated.cshtml, and explicit paths with those suffixes are rejected. Rename the file to format it.

Diagnostics

Code Meaning
RF010 Could not find the opening brace for an @code / @functions block.
RF011 Unclosed @code / @functions block.
RF012 Roslyn failed to format an @code block.
RF013 Inline @{ } with markup, or trailing content after @code / @functions.
RF020 Unexpected closing tag.
RF021 Unclosed element.
RF022 Unmatched closing brace.
RF023 Unterminated markup tag.
RF024 Unterminated comment.
RF025 Unclosed Razor brace.
RF026 Unterminated Razor expression or header.
RF027 @code template boundaries could not be resolved; the block was preserved.
RF999 Unexpected formatter failure.

Safety

  • C# is formatted by Roslyn; RazorFmt only locates the spans.
  • The structural check is bounded and fails closed: on a detected error it returns the original text, and --write leaves the file untouched.
  • Supported fixtures assert idempotency and non-whitespace preservation.
  • Output is deterministic and does not depend on the network, the SDK, or the current project.

Run --check first in CI and review a --diff before the first bulk --write.

- run: dotnet tool install --global RazorFmt.Cli
- run: razorfmt --check .

Editors

VS Code and Visual Studio setup is in editors/README.md.

The VS Code extension registers a document formatter for **/*.razor and **/*.cshtml, supports format-on-save, and applies no edits when the CLI reports an error.

API

using RazorFmt.Core;

var formatter = new RazorFormatter();
var result = formatter.Format(source, new FormatterOptions { IndentSize = 4 });

if (result.Success)
    Console.Write(result.FormattedText);

foreach (var diagnostic in result.Diagnostics)
    Console.Error.WriteLine(
        $"{diagnostic.Code}: {diagnostic.Message} (line {diagnostic.Line})");

FormatterOptions exposes IndentSize, UseTabs, NewLine, NormalizeBlankLines, FormatCSharp, SplitTags, WrapAttributes, MaxLineLength, and SplitCode.

Known limitations

  • @code blocks that combine @<...> templates with direct markup lambdas (markup written directly in a C# lambda body) are preserved, because the remaining C# cannot be parsed as a whole.
  • Nested @<...> templates are not rewritten.
  • Mixed Razor/markup @{ ... } bodies are indented but not C#-formatted.
  • --split-tags does not split C# statements inside @code blocks.
  • The structural check is not a full Razor or HTML parser. Tag Helpers, the full HTML content model, and whitespace-sensitive contexts beyond the listed raw elements are not fully validated.
  • Optional end tags are handled conservatively for indentation, not as a complete HTML parser.
  • Idempotency and non-whitespace preservation are tested for supported shapes; they are not guaranteed for arbitrary Razor source.

Benchmarks

The benchmark harness formats a directory and reports total and per-format time and allocations:

# Defaults to RazorFmt.Core.Tests/Fixtures with 5 iterations.
dotnet run --project RazorFmt.Benchmarks -c Release

# Another corpus and iteration count.
dotnet run --project RazorFmt.Benchmarks -c Release -- path/to/project 3

The fixture benchmark and the seeded fuzz tests run in CI.

Status

Current release: 0.7.0. .razor and .cshtml are supported, including MVC tag helpers and Blazor components. See CHANGELOG.md for release notes.

License

MIT. See LICENSE.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

Version Downloads Last Updated
0.7.0 104 11/13/2026
0.6.0 103 11/4/2026
0.3.0 96 11/3/2026
0.2.1 82 11/3/2026
0.2.0 93 11/3/2026
0.1.1 97 11/3/2026
0.1.0 106 11/2/2026