Wednesday, July 18, 2007

Indent code and surround with braces

This macro saves a bit of time by adding braces around a piece of code and indenting the block -- something I do a dozen times in a normal day.

' Takes the current selection, indents it, and surrounds with braces.
Sub CreateCodeBlock()
CreateCodeBlock_Helper("{", "}")
End Sub

' Takes the current selection, indents it, and surrounds it with startOfBlock and endOfBlock
Sub CreateCodeBlock_Helper(ByVal startOfBlock As String, ByVal endOfBlock As String)
Dim sel As TextSelection = DTE.ActiveDocument.Selection
Dim objAnchor As VirtualPoint = sel.AnchorPoint
Dim bottomPoint As VirtualPoint = sel.BottomPoint

Dim trimmedString As String = sel.Text.TrimStart()
Dim numChars As Integer = sel.Text.Length - trimmedString.Length
Dim spaceString As String = sel.Text.Substring(0, numChars)

objAnchor.CreateEditPoint().Insert(spaceString + startOfBlock + vbCrLf)
bottomPoint.CreateEditPoint().Insert(spaceString + endOfBlock + vbCrLf)
sel.Indent()
'sel.LineUp()


'sel.Text = "{" + vbCrLf + sel.Text + "}" + vbCrLf
End Sub


Once I started to write a whole library of code that was in a namespace, I found it useful to extend the macro so that it indents everything and surrounds it with a "namespace XXX {". The closing brace at the end includes a comment that says "} // end of namespace XXX"

' Takes the current selection and surrounds it with "namespace xxx {" and "}"
' (after prompting user for the namespace name xxx)
Sub SurroundWithNamespace()
Dim name As String
name = InputBox("Namespace name")
CreateCodeBlock_Helper("namespace " + name + vbCrLf + "{", vbCrLf + "} // end of namespace " + name)

End Sub