Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there some way to automatically indent VB.NET code in a text file

I would like to correctly indent some VB.NET code contained within a text file. Is there some way to do this?

e.g. Start with this:

Public Shared Function CanReachPage(page As String) As Boolean
Try
Using client = New WebClient()
Using stream = client.OpenRead(page)
Return True
End Using
End Using
Catch
Return False
End Try
End Function

finish up with this:

Public Shared Function CanReachPage(page As String) As Boolean
    Try
        Using client = New WebClient()
            Using stream = client.OpenRead(page)
                Return True
            End Using
        End Using
    Catch
        Return False
    End Try
End Function

Everything I have searched for has so far led me to the IndentedTextWriter Class but the only examples I have found are to manually indent lines like this: .NET Console TextWriter that Understands Indent/Unindent/IndentLevel

Extra credit: I would also like to add the correct spacing as well if possible:

e.g Dim i As String="Hello"+"GoodBye" -> Dim i As String = "Hello" + "GoodBye"

like image 758
Matt Wilko Avatar asked Feb 11 '14 09:02

Matt Wilko


2 Answers

If you're using Visual Studio (I'm looking at VS 2010 at the moment; I don't know offhand what earlier versions did) then you can go to the Edit->Advanced->Format Document and it should take care of the indentation and spacing for you.

Note that this works for any type of document that Visual Studio understands. I regularly use this trick to format XML documents into something legible.

like image 193
shooley Avatar answered Oct 26 '22 06:10

shooley


If you're okay with using pre-release software, you could use Roslyn:

Dim parsed = Syntax.ParseCompilationUnit(text)
Dim normalized = parsed.NormalizeWhitespace()
Console.WriteLine(normalized)
like image 44
svick Avatar answered Oct 26 '22 05:10

svick