Visual Studio copy selection macro
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
Perfect, I’ve been missing the “duplicate line” keystroke in my text editor – have it hooked up in vis studio now.
Well, this works sometimes. Sometimes not. For example, try to copy the line with “This is my class” text:
///
/// This is my class
///
public class MyClass
{
}
Your code appends /// at the end, because it doesn’t handle Visual Studio automated text insertion.
Will see if I have some time to fix it. I have had some problems with trailing spaces that keep adding when using the script multiple times on selection.
Added a short check to see if any auto insertion occurred. And if so it get’s deleted before pasting.