Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Visual Studio code formatting work properly for Razor markup?

Or, should I rather ask, when will VS code formatting work properly for Razor markup? The formatting works for most structures, but it seems to choke on 'if' blocks. The code below is as it is formatted by VS. It is very easy to fix this case, with one more indent, but I nicely accepted the formatting in everyday use, and like to use it often for the bulk of my code, so I'd rather avoid manual formatting if possible. Right now I just leave it as VS formats it.

@{      if (User.Identity.IsAuthenticated)     {     <text>Hello </text>     @Html.Display("@ViewBag.UserName") <text> - </text>     @Html.ActionLink("Sign Out", "LogOff", "Account", null, new { style = "font-weight: bold;" })     }  } 

I think it's important for readability that, e.g. in the above, the body of the if block is indented, besides just looking nicer.

like image 955
ProfK Avatar asked Aug 01 '11 17:08

ProfK


People also ask

How do I fix code formatting in Visual Studio?

The code formatting is available in Visual Studio Code through the following shortcuts: On Windows Shift + Alt + F. On Mac Shift + Option + F. On Linux Ctrl + Shift + I.

How do I fix formatting in Visual Studio 2019?

Auto formatting settings in Visual Studio Show activity on this post. Select the text you want to automatically indent. Click menu Edit → Advanced → *Format Selection, or press Ctrl + K , Ctrl + F . Format Selection applies the smart indenting rules for the language in which you are programming to the selected text.


2 Answers

Be sure to set the editor to use space characters and not tabs. The editor seems to completely lose its mind when tabs are used. This is a shame because all those space characters end up in the actual HTML output, greatly increasing the data transfer size. What I do is manually supplement the automatic formatting as I type. Not ideal, but hopefully Microsoft will have this figured out for the next service pack.

like image 125
Charles Burns Avatar answered Sep 22 '22 10:09

Charles Burns


I found one "solution" that allows you to continue using tab indentation and have correct formatting. It's more of a pattern. The key is to use razor code blocks instead of inline code.

So for example, replace the following:

<div>     <div>         @if (true)         {             <b>Hi</b>         }     </div> </div> 

with:

<div>     <div>         @{             if (true)             {                 <b>Hi</b>             }         }     </div> </div> 

The latter will format correctly, but the former won't.

Keep in mind, the formatting isn't perfect, but it's better than before.

like image 39
Josh Mouch Avatar answered Sep 23 '22 10:09

Josh Mouch