Feed on
Posts
Comments

Many developers were surprised to learn that Visual Studio 2012 dropped Macro support. Microsoft says they dropped the feature because it was only used by a tiny fraction of VS programmers.  Guess what. I’m one of those developers and  I’m still mourning the loss, as I had a library of custom macros created during the last ten years.

My favorite macro was my CleanCurrentDoc macro which, as the name implies, performed some common code cleanup tasks.  One feature of the macro was the ability to remove two adjacent blank lines.  I’m not against having blank lines my code. I like to leave single blank lines in my editor, to delineate blocks of code, but I never want to see two or more adjacent blank rows.

In other words, I want to take this code:

  Line 1
  <empty>
  Line 2
  <empty>
  <empty>
  <empty>
  Line 3

 

And format it into this:

  Line 1
  <empty>
  Line 2
  <empty>
  Line 3

Use QuickReplace to solve the problem

Someday I’ll create a Visual Studio Extension to solve the problem, but the immediate solution is to use the Quick Replace tool. Visual Studio can use Regular Expressions in the Search operations.  That’s the key to making the replacement work.  If you are a veteran of earlier versions of Visual Studio  (prior to VS 2012) be warned that the Regex syntax has changed.

Apparently the older version of Visual Studio used a application specific Regex syntax. Here is the necessary Regex.

^(?([^\r\n])\s)*\r?$\r?\n^(?([^\r\n])\s)*\r?$\r?\n

Beautiful, isn’t it?  Disappointed smile

image

 

Regular Expression Books

Visual Studio Training

2 Responses to “Remove adjacent empty code lines with QuickReplace in VS 2012”

  1. Hey,
    Most of the Macro’s that I’ve seen reinvented the wheel – VS has tons of extensions that already do all that things you need.
    I suggest CodeMaid (link bellow) – it will do much more than just remove blank lines ;)

    http://visualstudiogallery.msdn.microsoft.com/76293c4d-8c16-4f4a-aee6-21f83a571496

    • Walt Ritscher says:

      I think I tried Code Maid a few months back. I can’t remember why I removed it. I’m also a long time user of CodeRush and it has some useful additions.