Click here to Skip to main content
6,595,444 members and growing! (19,954 online)
Email Password   helpLost your password?
General Programming » Macros and Add-ins » VS.NET Macros     Intermediate

A nice macro that automates the task of making regions in C# code

By Phillip H. Blanton

At ComponentScience where I work, we heartily embrace the use of regions to logically separate our code into meaningful blocks. After doing it manually for a couple of years, I decided to write myself a little macro to make my life easier.
C#, VB, VBScript, Windows, .NET 1.1VS.NET2003, Dev
Posted:3 Dec 2004
Updated:3 Jan 2005
Views:66,017
Bookmarked:48 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
24 votes for this article.
Popularity: 6.33 Rating: 4.59 out of 5

1
1 vote, 4.2%
2
1 vote, 4.2%
3
3 votes, 12.5%
4
19 votes, 79.2%
5

Contents

Introduction

At ComponentScience, we heartily embrace the use of regions to logically separate our code into meaningful blocks. After doing it manually for a couple of years, I decided to write myself a little macro to make my life easier. After a little research, I found a couple of examples of how to manipulate Visual Studio's code editor. The result is the following macro that I use to regionify my code.

I have also included instructions on how to install it into Visual Studio and assign it to a hotkey. I use Alt+R because it wasn't used in the Visual Studio text editor, and it made sense to me.

You are welcome to use it all you want, give it to your friends and even claim to have written it yourself if you want.

Note: I only use this macro in C# files. If you want to use it in VB, then you need to uncomment the VB sections and comment out the C# sections. If anybody has any tips on how to modify the script to detect the language being used, let me know and I will modify the script accordingly. I'm sure there is an easy way, I just haven't researched it because I don't care. The VB parts do work in VB code though. I tested it that much.

Update: After posting this article on CodeProject, I got some feedback from readers about how to test for the language being used, make the padding better, and handle tabs as well as spaces. I have updated the macro accordingly.

Even more update!: The users on CodeProject have done a wonderful job of tweaking the macro! We now have a really nice regioning macro. I am very happy with the feedback I have gotten from the CodeProject community. Special thanks (in no particular order) goes to RussKie, simonech, Hrusikesh, ERobishaw, isler-j, and SvenRieke. These guys embody the spirit of cooperative development.

Macro Code

  Sub MakeRegion()
    Regions.MakeRegion()
  End Sub

  Public Class Regions
    ' MakeRegion inserts #region and #endregion tags

    ' around selected text in the VS editor.

    Shared Sub MakeRegion()
      Dim rName As String = ""
      Dim pad As String = ""
      Dim junk As String
      Dim count, i As Integer
      Dim startpoint, endpoint, tmppoint As EditPoint

      With DTE.ActiveDocument.Selection
        startpoint = .TopPoint.CreateEditPoint()
        endpoint = .BottomPoint.CreateEditPoint
      End With

      If startpoint.EqualTo(endpoint) Then
        Exit Sub
      End If

      'ELR: ADDED THIS, to move the startpoint to the start of the line

      'so that the Pad function works correctly

      If Not startpoint.AtStartOfLine Then
        startpoint.StartOfLine()
      End If

      'IV 2004-12-13: rName = InputBox("Region Name:")

      rName = InputBox("Region Name:", "Pick a name", _
        GetDesc(DTE.ActiveDocument.Selection.TopPoint.CreateEditPoint()))

      DTE.UndoContext.Open("Insert A Region")
      Try
        junk = startpoint.GetText(startpoint.LineLength)

        pad = String.Empty
        For count = 0 To junk.Length - 1
          If junk.Substring(count, 1).Equals(" ") Or _
          junk.Substring(count, 1).Equals(vbTab) Then
            pad += junk.Substring(count, 1)
          Else
            Exit For
          End If
        Next

        'ELR: ADDED Test for Languages

        If DTE.ActiveDocument.Language = "CSharp" Then
          ' C Sharp Code

          startpoint.Insert(String.Format("{0}#region {1}{2}", _
            pad, rName, vbCrLf))
          If endpoint.LineLength = 0 Then
            endpoint.Insert(String.Format("{0}#endregion // {1}{2}", _
              pad, rName, vbCrLf))
          Else
            endpoint.Insert(String.Format("{0}#endregion // {1}{2}", _
              vbCrLf & pad, rName, vbCrLf))

          End If
        Else
          ' VB Code

          startpoint.Insert(String.Format("{0}#Region ""{1}""{2}", _
            pad, rName, vbCrLf))
          If endpoint.LineLength = 0 Then
            endpoint.Insert(String.Format("{0}#End Region '{1}{2}", _
              pad, rName, vbCrLf))
          Else
            endpoint.Insert(String.Format("{0}#End Region ' {1}{2}", _
              vbCrLf & pad, rName, vbCrLf))
          End If
        End If
      Finally
        DTE.UndoContext.Close()
      End Try
    End Sub

    ' IV: Get the description from the 1st line of code in the region

    ' i.e. ignore c# comment tags (///) or take 1st line of the comments (//)

    ' Requires adjustments for VB and other langs

    Private Shared Function GetDesc(ByVal startpoint As EditPoint) As String
      Dim line As String = ""
      Dim tmppoint As EditPoint

      line = startpoint.GetText(startpoint.LineLength)
      If (line.Length > 0) Then
        line = line.TrimStart(" ", vbTab)
        If DTE.ActiveDocument.Language = "CSharp" Then
          If (line.StartsWith("///")) Then
            tmppoint = startpoint
            tmppoint.LineDown()
            line = GetDesc(tmppoint)
          ElseIf (line.StartsWith("//")) Then
            line = line.TrimStart("//", " ")
          End If
          line = line.Replace("{", String.Empty)
        End If
        line = line.TrimEnd(" ", vbTab)
      End If
      Return line
    End Function
  End Class

How to use

Installation

To install the macro, open up Visual Studio and follow these directions...

  • Open up the Macro Explorer by pressing Alt+F8.
  • Right-click on your MyMacros icon and select "New Module".
  • Give the new module a meaningful name and save it.
  • Right-click on the new module and select "New Macro".
  • Replace "Sub Macro1()" through "End Sub" with the code above.
  • Save the macro file.

Hot Key Assignment

To assign the new MakeRegion macro to Alt+R:

  • In Visual Studio, Click "Tools | Options" from the menu.
  • Open the "Environment" page and select "Keyboard".
  • Click [Save As�] and save the default keyboard mapping with a meaningful name. (You can't modify the default keyboard mapping.)
  • In the "Show Commands Containing:" field, type "MakeRegion".
  • Select the new MakeRegion macro from the list.
  • In the "Use new shortcut in:" field, select "Text Editor".
  • In the "Press shortcut key(s):" field, press "Alt+R".
  • Click the [Assign] button.
  • Click the [OK] button.

You're done! Now, open up the text editor, select some text, and press [Alt+R]. It will take a few seconds to show up the first time it is run. When the dialog pops up, type the name of the region and press Enter.

Happy Regioning!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Phillip H. Blanton


Member
I am a co-founder and CTO of ComponentScience Incorporated (www.ComponentScience.net); where my time is spent designing and developing component libraries for the Microsoft .NET framework.

I first began programming DOS-based, multiuser point of sale systems in 1989 using C and Turbo Pascal. I dabbled in Windows programming with OWL, and took it up full-time with the release of Delphi 1.

Before co-founding ComponentScience, I was employed as a senior software engineer with TurboPower Software Company, where I helped to create award-winning UI component libraries for Borland Delphi and C++ Builder. Now I am a 100% dot net junkie.
Occupation: Web Developer
Location: United States United States

Other popular Macros and Add-ins articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 33 (Total in Forum: 33) (Refresh)FirstPrevNext
GeneralStill the best. Pinmemberstano18:24 4 Oct '08  
GeneralWhy not just use Resharper? PinmemberSean Goodpasture6:00 17 Oct '06  
GeneralRe: Why not just use Resharper? PinmemberPhillip H. Blanton6:25 17 Oct '06  
GeneralRe: Why not just use Resharper? PinmemberSean Goodpasture6:48 17 Oct '06  
GeneralRe: Why not just use Resharper? PinmemberPhillip H. Blanton12:02 7 Oct '08  
Generalmodify for the Try Catch.. Pinmembermattmaxx6:50 15 Mar '06  
GeneralAnother macro for region creations PinmemberDan Händevik9:01 13 Mar '05  
Generalsmall request PinmemberNicoRi8:27 20 Jan '05  
GeneralRe: small request PinmemberPhillip H. Blanton7:25 11 Dec '05  
GeneralSmall addition PinmemberRussKie20:15 16 Jan '05  
GeneralNeed to updtae PinmemberArun Manglick20:08 4 Jan '05  
GeneralUpdate Need PinmemberArun Manglick20:07 4 Jan '05  
GeneralUpdate Needed!!! PinmemberPhillip H. Blanton13:37 13 Dec '04  
GeneralLatest macro?? PinmemberMisty_Blue7:30 13 Dec '04  
GeneralRe: Latest macro?? PinmemberRussKie12:42 13 Dec '04  
GeneralRe: Latest macro?? PinmemberPhillip H. Blanton13:31 13 Dec '04  
GeneralLittle variation PinmemberRussKie12:39 12 Dec '04  
GeneralRe: Little variation PinmemberSvenRieke0:28 13 Dec '04  
GeneralStill a problem Pinmembersimonech4:28 12 Dec '04  
GeneralRe: Still a problem Pinmembersimonech4:33 12 Dec '04  
GeneralRe: Still a problem PinmemberPhillip H. Blanton12:58 13 Dec '04  
GeneralLittle bug PinmemberHrusikesh9:42 9 Dec '04  
GeneralRe: Little bug Pinmemberisler-j4:30 10 Dec '04  
GeneralLatest Macro Code PinmemberPhillip H. Blanton8:39 8 Dec '04  
GeneralRe: Latest Macro Code PinmemberPhillip H. Blanton8:41 8 Dec '04  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 3 Jan 2005
Editor: Smitha Vijayan
Copyright 2004 by Phillip H. Blanton
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project