Search code examples
visual-studiomacrosvisual-studio-macros

"New Scope" Macro for Visual Studio


I'm trying to create a new macro that takes the currently selected text and puts curly braces around it (after making a newline), while, of course, indenting as needed.

So, for example, if the user selects the code x = 0; and runs the macro in the following code:

if (x != 0) x = 0;

It should turn into:

if (x != 0) 
{
    x = 0;
}

(Snippets don't help here, because this also needs to work for non-supported source code.)

Could someone help me figure out how to do the indentation and the newlines correctly? This is what I have:

Public Sub NewScope()
    Dim textDoc As TextDocument = _
                CType(DTE.ActiveDocument.Object("TextDocument"), TextDocument)
    textDoc.???
End Sub

but how do I figure out the current indentation and make a newline?


Solution

  • Sub BracketAndIndent()
        Dim selection = CType(DTE.ActiveDocument.Selection, TextSelection)
    
        ' here's the text we want to insert
        Dim text As String = selection.Text
    
        ' bracket the selection;
        selection.Delete()
    
        ' remember where we start
        Dim start As Integer = selection.ActivePoint.AbsoluteCharOffset
    
        selection.NewLine()
        selection.Text = "{"
        selection.NewLine()
        selection.Insert(text)
        selection.NewLine()
        selection.Text = "}"
    
        ' this is the position after the bracket
        Dim endPos As Integer = selection.ActivePoint.AbsoluteCharOffset
    
        ' select the whole thing, including the brackets
        selection.CharLeft(True, endPos - start)
    
        ' reformat the selection according to the language's rules
        DTE.ExecuteCommand("Edit.FormatSelection")
    End Sub