Remap CapsLock(tap) to ESC and CapsLock(hold) to CTRL in OS X Lion

For vim purposes, I'd like to remap CapsLock to CTRL when used in combination with other keys and ESC when used in isolation.

None of the existing solutions give both functionality - only one or the other.

Thanks!


Step by step instructions:

  1. Install both PCKeyboardHack and KeyRemap4MacBook. It will prompt you to reboot after installing the apps.
  2. Disable Caps Lock. Go to System Preferences -> Keyboard -> Modifier Keys. Set Caps Lock to "No Action".
  3. In PCKeyboardHack set Cap Lock to Control_L by changing the Caps Lock keycode to 59.
  4. In KeyRemap4MacBook, toggle "Control_L to Control_L (+ when you type Control_L only, send Escape". I searched for "Control_L escape" and it showed up near the top.

UPDATE:

On High Sierra, this functionality is built into the new Karabiner Elements.

Follow the install instructions, then:

  1. Open Karabiner-Elements
  2. Click "Complex Modifications"
  3. Click "Add Rule"
  4. Click "Import more rules from the internet"
  5. On the resultant web page, look for "Modifier Keys > Change caps_lock Key" and import the configuration.
  6. Profit!

This worked for me on OSX 10.9:

  1. Set Caps Lock to Control. Go to System Preferences -> Keyboard -> Modifier Keys. Set Caps Lock to "^ Control",
  2. Install KeyRemap4MacBook,
  3. In KeyRemap4MacBook, toggle "Control_L to Control_L (+ when you type Control_L only, send Escape".