Thursday, June 25, 2009

Removing Empty Lines From Code In Visual Studio

There are plenty of source code formatters out there, but after searching for 3 seconds and not finding any free ones that were better than the in-built VS source code formatter, i came up with the following regex that will at least remove all redundant lines from my colleagues lovely source code:

Replace ^\n$ with (nothing)

To use it, bring up the Replace dialog (Ctrl+H for me, depends on the environment profile you are using), tick the box at the bottom to use regular expressions, select "entire solution" to process all files (or set to your needs), and type the above regex into the "find" box and hit "Replace All". VOILA! All redunant empty lines are gone.

Of course this is a very simple regex and does not take into account the context of the blank line, so you may still end up with single blank lines where they are not needed (inside methods for example). But its a start - if anyone has a better regex for C# that conforms to Microsoft's recommendations please post. Also post any fantastically configurable free tools that you know of.

Ideally i think the view of code should be independant from the stored format of the code. In other words, VS should give more formatting options and apply it automatically when a file is viewed, so every developer can 'view' the code the way they like, but under the hood its stored in source control in a standard format - like a model/view separation concept

No comments: