Delete line, duplicate line, key bindings in Xcode and Mac OS X text system

14th December 2009 13:05:30 by Richard Bennett

Firstly you've probably read my other concerns about delete line and duplicate line, in that I can't believe any modern IDE or text editor wouldn't include these as standard. Luckily however the Mac OS X text system does include modifiable key bindings. There's a couple of posts on the web about how to do it, but they're either too vague to be useful, or they implement the commands clumsily.

Here's a step by step of how I do key bindings for delete line and duplicate line in Xcode:

  1. Create the directory ~/Library/KeyBindings if it doesn't already exist
  2. Create a file called PBKeyBindings.dict
  3. Paste the following into the file and save it:
    {
        "~d" = (
            "selectLine:",
            "copy:",
            "moveToBeginningOfLine:",
            "paste:",
        );
        "~D" = (
            "selectLine:",
            "copy:",
            "moveToBeginningOfLine:",
            "paste:",
        );
        "~e" = (
            "selectLine:",
            "cut:"
        );
        "~E" = (
            "selectLine:",
            "cut:"
        );
    }
  4. Launch Xcode, select the Preferences menu item and select the Key Bindings tab. Change the Key Binding Sets drop down list to "Xcode Default". Key Bindings in PBKeyBindings.dict won't work if you have a custom set selected
  5. Quit and relaunch Xcode.

This gives you option-e and option-E to delete the current line, and option-d and option-D to duplicate the current line. If you want control instead of option, then change the tilde "~" in the key binding dict to caret "^", and then quit and relaunch Xcode.

If you add these definitions to ~/Library/KeyBindings/DefaultKeyBinding.dict as well, then they should work in other IDEs and editors as well.