Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete Matching Braces in Visual Studio

In Visual Studio I can jump from/to opening/closing brace with the Control+] shortcut.

Is there a shortcut that will allow me to delete both braces at once (maybe with a macro/extension)?

e.g.

foo = ( 1 + bar() + 2 );

When I am on the first opening brace I would like to delete it and its matching brace to get

foo = 1 + bar() + 2;
like image 376
laktak Avatar asked Mar 27 '12 20:03

laktak


3 Answers

There isn't an inherent way to do this with Visual Studio. You would need to implement a macro in order for this.

If you choose the macro route you'll want to get familiar with the Edit.GoToBrace command. This is the command which will jump you from the current to the matching brace. Note it will actually dump you after the matching brace so you may need to look backwards one character to find the element to delete.

The best way to implement this as a macro is to

  • Save the current caret position
  • Execute Edit.GoToBrace
  • Delete the brace to the left of the caret
  • Delete the brace at the original caret position
like image 189
JaredPar Avatar answered Oct 20 '22 23:10

JaredPar


Make a macro to press Ctrl+] twice and then backspace, then Ctrl+minus and a delete. The Ctrl+minus moves the cursor back in time.

like image 4
SimpleVar Avatar answered Oct 21 '22 01:10

SimpleVar


It's not quite as simple as JaredPar suggested but I'm no Macro expert either.

This works for (), {} and []

Sub DeleteMatchingBrace()
    Dim sel As TextSelection = DTE.ActiveDocument.Selection
    Dim ap As VirtualPoint = sel.ActivePoint

    If (sel.Text() <> "") Then Exit Sub
    ' reposition
    DTE.ExecuteCommand("Edit.GoToBrace") : DTE.ExecuteCommand("Edit.GoToBrace") 

    If (ap.DisplayColumn <= ap.LineLength) Then sel.CharRight(True)

    Dim c As String = sel.Text
    Dim isRight As Boolean = False
    If (c <> "(" And c <> "[" And c <> "{") Then
        sel.CharLeft(True, 1 + IIf(c = "", 0, 1))
        c = sel.Text
        sel.CharRight()
        If (c <> ")" And c <> "]" And c <> "}") Then Exit Sub
        isRight = True
    End If

    Dim line = ap.Line
    Dim pos = ap.DisplayColumn
    DTE.ExecuteCommand("Edit.GoToBrace")
    If (isRight) Then sel.CharRight(True) Else sel.CharLeft(True)

    sel.Text = ""
    If (isRight And line = ap.Line) Then pos = pos - 1
    sel.MoveToDisplayColumn(line, pos)
    sel.CharLeft(True)
    sel.Text = ""
End Sub

Then add a shortcut to this macro in VS.

like image 3
laktak Avatar answered Oct 21 '22 01:10

laktak