Skip to content

Instantly share code, notes, and snippets.

@git-hub-tig
Forked from Sidelobe/duplicate_line_xcode.md
Created February 18, 2022 15:06
Show Gist options
  • Save git-hub-tig/2354931da991d189cd137975831817a6 to your computer and use it in GitHub Desktop.
Save git-hub-tig/2354931da991d189cd137975831817a6 to your computer and use it in GitHub Desktop.
Xcode - Duplicate Line key binding

Xcode line duplication (without overwriting your clipboard)

I find this shortcut extremely useful in Xcode: duplicate one or several lines without losing what you have on the clipboard.

Bind keys to duplicate lines in Xcode

  1. To add custom key bindings in Xcode, you have to edit this file (su privileges required): '/Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/Current/Resources/IDETextKeyBindingSet.plist

I add the following new key at the bottom:

<key>Custom Commands</key>
<dict>
    <key>Duplicate Current Lines Down</key>
    <string>selectParagraph:, delete:, yank:, moveToBeginningOfParagraph:, yank:, moveUp:, moveToEndOfParagraph:</string>
</dict>
  1. Open Xcode and go to Xcode Preferences -> Key Bindings
  2. filter for Duplicate Current Lines Down, add a shortcut for it. I use the chord shift + ctrl + command + , which is not taken yet and reminds me of Eclipse ;-)

NOTE: you will have to do this every time Xcode is updated -- that's why you might as well write a shell script to automate most of it.

Automatization

NOTE: you will have to do this every time Xcode is updated -- that's why you might as well write a shell script to automate it.

I'm not doing a full automatization yet... I like doing the last step manually.

Save the following in bash shell script (I called it prepareXcodeKeybindingsForEditing.sh) and then call it from terminal with sudo sh prepareXcodeKeybindingsForEditing.sh everytime you update Xcode. It opens an editor (atom in my case, edit to your liking...) and prints the XML you need to copy-paste for you in terminal.

path='/Applications/Xcode.app/Contents/Frameworks/IDEKit.framework/Versions/Current/Resources/'
bindingsFile=$path'IDETextKeyBindingSet.plist'

sudo chmod 755 $path

if [ ! -f $bindingsFile ]; then
    echo "Bindings file doen't exist"
fi
sudo chmod 664 $bindingsFile
sudo open -a atom $bindingsFile

echo "Now paste the following:"
echo "<key>Custom Commands</key>
<dict>
    <key>Duplicate Current Lines Down</key>
    <string>selectParagraph:, delete:, yank:, moveToBeginningOfParagraph:, yank:, moveUp:, moveToEndOfParagraph:</string>
</dict>"
echo ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment