Archive

Posts Tagged ‘selection’

Visual Studio copy selection macro

April 15th, 2010 4 comments

I use the copy line / copy selection under cursor in NetBeans a lot. So I created this macro for use in Visual Studio that provides this functionality. If no line is selected the current line where the cursor is placed will be copied.
When a selection is made the selection will be copied and pasted below the selection. Afterwards the selection will be remade so you can repeat the action immediately.

Below is the VB snippet.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics
 
Public Module Famvdploeg
    ' Copy the current line or selection
    Sub CopySelection()
        Dim selection As String
        Dim lines As Array
 
        ' Select current line if nothing is selected
        If String.IsNullOrEmpty(DTE.ActiveDocument.Selection.Text) Then
            DTE.ActiveDocument.Selection.StartOfLine(0)
            DTE.ActiveDocument.Selection.EndOfLine(True)
        End If
 
        ' Store some variables
        selection = DTE.ActiveDocument.Selection.Text
        lines = Split(selection, vbCrLf)
 
        ' Perform the copy+paste action depending on how selection is made
        If String.IsNullOrEmpty(lines(lines.Length - 1)) Then
            DTE.ActiveDocument.Selection.Copy()
            DTE.ActiveDocument.Selection.EndOfLine(0)
            DTE.ActiveDocument.Selection.StartOfLine(0)
            DTE.ActiveDocument.Selection.Paste()
        Else            
            DTE.ActiveDocument.Selection.Copy()
            DTE.ActiveDocument.Selection.EndOfLine()
            DTE.ActiveDocument.Selection.NewLine()
            ' Sanitize any auto text insertion
            DTE.ActiveDocument.Selection.StartOfLine(0)
            DTE.ActiveDocument.Selection.EndOfLine(True)
            If Not String.IsNullOrEmpty(DTE.ActiveDocument.Selection.Text()) Then
                DTE.ActiveDocument.Selection.Delete()
            End If
            DTE.ActiveDocument.Selection.StartOfLine(0)
            DTE.ActiveDocument.Selection.Paste()
        End If
 
        If lines.Length > 1 Then
            ' ReSelect the text so we can repeat the action immediately
            DTE.ActiveDocument.Selection.LineUp(False, lines.Length - 1)
            DTE.ActiveDocument.Selection.StartOfLine(0)
            DTE.ActiveDocument.Selection.LineDown(True, lines.Length - 1)
            If Not String.IsNullOrEmpty(lines(lines.Length - 1)) Then
                DTE.ActiveDocument.Selection.EndOfLine(True)
            End If
        Else
            DTE.ActiveDocument.Selection.StartOfLine(0)
        End If
    End Sub
End Module