Pure Heart, Clean Code – Part 2
A few months back, I gave a short tutorial on how to integrate a code formatter / beautifier (uncrustify) into Xcode 3. Unfortunately (or fortunately), an alpha variant of an all new and improved Xcode 4 is available to members of the ADC. In an attempt to not break any NDAs, I’ll try to document this method in a generic way. Fortunately, it requires no configuration within Xcode 4 itself.
Interestingly, the method I’m about to discuss is also valid in Xcode 3, but not as efficient as the method I described in the previous article, as it doesn’t allow for a full document “cleansing” in place (one must select the code to be cleansed first). Before Xcode 4 finds its way to a final release, I imagine we’ll have many other options available to us – including one that will allow us to fully replicate the previous functionality.
The gist of the following method is to use an Automator script that calls uncrustify and attach it to Xcode as Service that shows up in the Services menu. Tony Arnold has created three Automator workflows to provide similar functionality. I really don’t like how all of them work – purely due to the limitations of the method used. For example, Tony’s Uncrustify Current Document mimics the original functionality from my initial article but instead of processing the document live, processes the underlying file, causing some odd state in Xcode and a fairly unpleasant user experience. Therefore, I’ll just discuss how to create the Uncrustify Selected Text variant. If you want, you can just bypass the next paragraph and use Tony’s version, but come back afterwards because I have one more additional tip.
I’ve never really used the Automator before. It’s actually pretty slick. First, open Automator and choose to create a new Service template. This will create a new Services based workflow. You will select text and Xcode as the parameters to the new service workflow. You will drag one Action, Run Shell Script and enter the following as the script:
/usr/local/bin/uncrustify -q -c ~/uncrustify.cfg -l oc
The astute notice this is pretty much the same from the previous article. Save your new workflow to ~/Library/Services/ as Uncrustify Selected Text. Now, when running Xcode, a new option will become available in the Services menu when text is selected in the Xcode editor, allowing you to uncrustify your selection.
Oh, almost forgot the added bonus tip. Previously, we assigned a keyboard shortcut to the uncrustify task. There isn’t a direct method in Automator to assign a shortcut, but we can add it in System Preferences > Keyboard under Keyboard Shortcuts. Select Application Shortcuts and add a shortcut, selecting Xcode as the Application and Uncrustify Selected Text as the Menu Title. Pick your favorite keyboard shortcut, and you’re ready to go!