Xcode trick: Creating a shortcut to duplicate a line
Friday, May 14th, 2010A feature I love in TextMate that is missing in Xcode is the ability to duplicate a line of text with a simple two-key combo. Sure, it’s possible to select the line and then copy/paste, but it’s far too fiddly. For example, let’s say I wanted to add another line to this array:

I would have to type:
+ move to start of line
+ (shift-down) select line
+ copy
(down) (deselect)
+ paste
And I would end up with this.

That’s far too much work.
Digging through Xcode’s preferences I couldn’t find anything that would help, so I widened my search and stumbled on a page called Customizing the Cocoa Text System that showed me a way I could get this to work.
I created a directory:
mkdir ~/Library/KeyBindings
And created the file:
~/Library/KeyBindings/DefaultKeyBinding.dict
{
"^d" = ("moveToEndOfLine:",
"deleteToBeginningOfLine:", // line in kill buffer
"yank:", // put back what was deleted
"insertLineBreak:",
"moveToBeginningOfLine:",
"yank:"); // duplicate line
}
I restarted Xcode, and now a + (^d) duplicates the line. And I can easily add the new element to the array.

And it’s a system wide change, so it will work in many applications that have text input. (And doesn’t seem to screw up TextMate either.)
If you want to experiment with your own text input tweaks, there is a list of all selectors. You’ll need to restart whatever application you’re using to test after each change. You may also run into strange side effects. I ran into a problem with Xcode doing auto-intent after i added a newline with insertNewline:. Luckily, insertLineBreak: has the same effect, but seems to trick Xcode into not adding the extra whitespace on the duplicated line.
