Monday, March 09, 2009

Duplicate Line in Visual Studio

Visual Studio ships with many features built in. "Duplicate the current line" doesn't appear to be one of them for some strange reason.

CodeRush Express ships with a "duplicate line" function, but it's WAY too clever for it's own good. It tries to work out whether you're duplicating a line with a variable, function, etc, and act accordingly. If it can't understand your line (perhaps it's just a string), then it FAILS. Unfortunately it only understands about 40% of actual lines of code, so this severely limits it's usefulness.

This is stupid. I just want the equivalent of "copy/paste the current line be done with it", so without further ado, here's a macro to do it. You can then bind a keyboard shortcut to the macro, and get on with more important things.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports System.Diagnostics

Public Module Misc
    Sub Duplicate_Line()
        DTE.UndoContext.Open("Duplicate Line(s)")
        Try
            Dim ts As TextSelection = DTE.ActiveDocument.Selection
            Dim epStart As EditPoint = ts.TopPoint.CreateEditPoint()
            Dim epEnd As EditPoint = ts.BottomPoint.CreateEditPoint()

            Dim lineText As String = epStart.GetLines(epStart.Line, epEnd.Line + 1)

            epEnd.EndOfLine()
            epEnd.Insert(Environment.NewLine)
            epEnd.Insert(lineText)

            ts.MoveToLineAndOffset(epEnd.Line, epStart.LineCharOffset())
        Finally
            DTE.UndoContext.Close()
        End Try
    End Sub
End Module

PS: Why can't I write VS macros in C#? VB just looks so ugly :-(

9 comments:

Craig Box said...

Is Ctrl-Shift-End Ctrl-C End Enter Ctrl-V too many keypresses for how often you do this?

I do lots of Ctrl-Shift editing/word movement in muscle memory, so I'm slow in vim, but speedy in TextPad.

Orion Edwards said...

Is Ctrl-Shift-End Ctrl-C End Enter Ctrl-V too many keypresses for how often you do this?

Yes. Far too many

Jonas Kello said...

I agree that is far too may. Actually it can be acomplished by just two keypresses. Just standing on a line in VS.NET without having any of its text selected and pressing Ctrl+C, Ctrl+V will duplicate that line. You can hold Ctrl while pressing C, V which are next to each other on the keyboard so it is quite convenient. But then again two keypresses are more than one so your solution wins :-).

Orion Edwards said...

The thing I don't like about the clipboard solutions is that they destroy the clipboard. This doesn't :-)

Palmer Eldritch said...
This comment has been removed by the author.
Benjamin ADAM said...

Thanks, i can work now :)

Richard said...

Thanks, dude. I only wish the VC++ 2010 Express version I'm using for a class supported macros, lol :)

Unknown said...
This comment has been removed by the author.
Unknown said...

thanks for your tips, using CTRL + C + V to duplicate a line is very convenient