razor icon indicating copy to clipboard operation
razor copied to clipboard

Formatting doesn't work in Razor files in VS if file contains a Razor comment in a style element

Open jimmylewis opened this issue 2 years ago • 1 comments

Describe the bug: When a <style> block contains a Razor comment @* ... *@ all formatting on the page stops working.

Version used: Version 17.5.0 Preview 3.0 [33222.132.main]

To reproduce:

  1. Open this file in VS:
<h3>Bug</h3>
<style>
@* foo *@
.foo {}
</style>
<div>
foo
</div>
  1. Format Document or select any range and do Format Selection

Expected: Lines should get indented.

Actual: No indentation is changed

Additional context:

Using the VS Telemetry Monitor for LSP messages, I see this pattern of messages:

textDocument/formattingRazorLanguageServerClient-667215b5-a3a9-4473-8738Request2052
textDocument/formattingRazorLanguageServerClient-667215b5-a3a9-4473-8738Request1335
textDocument/formattingRazorLanguageServerClient-667215b5-a3a9-4473-8738Response1335
textDocument/formattingRazorLanguageServerClient-667215b5-a3a9-4473-8738Response2052

The inner response contains the result set of TextChanges that should be applied, but the outer response contains a null result. If I remove the @* *@ line it starts working fine (the outer contains the same set of changes as the inner).

jimmylewis avatar Dec 24 '22 06:12 jimmylewis

What is happened here is that we get the formatting changes back from the Html server, and after application the Razor document looks like this:

<h3>Bug</h3>
<style>
    @ * f o o * @
    .foo {
    }
</style>
<div>
    foo
</div>

So the Html server wants to put whitespace between each character in what it sees as ~~ ~~~ ~~ (representing @* foo *@. The whitespace after the @ is a Razor diagnostic, and we have a step in our formatting pipeline that says if any formatting operations change any non-whitespace characters, or change the diagnostics that are reported for a document, the operation is rejected. The latter is what is happening here.

So web tools is doing the right thing with what we gave it, and we're doing the right thing in rejecting a formatting operation that would break the Razor document.

This is essentially a dupe of https://github.com/dotnet/razor/issues/7891 in that the solution is the same: do actual Html source mapping so that we can generate better Html documents without the ~s in them, but will leave this open regardless, as its a good repro.

The workaround in the mean time is to use a CSS comment, and not a Razor comment.

davidwengier avatar Jan 09 '23 00:01 davidwengier