Code Formatting in Xcode 4

Posted on by in Development

Automatic indentation and cleanup of code seems to have improved in Xcode 4 (Editor menu – Structure – Re-Indent) but it still doesn’t offer full code reformatting or the flexibility of a tool like Uncrustify. If you’re used to having external code formatting in Xcode available you might be disappointed to find the User Scripts menu missing in Xcode 4.

Thankfully Tony Arnold demonstrated one possible solution with his Xcode 4 Uncrustify Automator Services. Here’s how you can get your external code formatting tool up and running again with Xcode 4.

Install Uncrustify (port install uncrustify, brew install uncrustify, or directly from http://uncrustify.sourceforge.net/)

Open Automator and create a new Service.

Creating a Service in Automator

Creating a new Automator Service

Inputs to Automator Services are more limited than the options available in Xcode 3’s User Scripts. To reformat selected text we can still pass the input from Xcode to a Run Shell Script action.

uncrustify -l OC -q -c ~/.uncrustify/uncrustify_obj_c.cfg
The "uncrustify selected text" service in Automator

Uncrustify Selected Text

To reformat open files we need to use AppleScript to get the paths to those files so that we can pass them to Uncrustify. I wasn’t able to find a reliable way to select only the currently visible source file so I settled on the following script to reformat all open and modified source files instead.

tell application id "com.apple.dt.Xcode"
	repeat with current_document in (source documents whose modified is true)
		set current_document_path to path of current_document
		set raw_source to text of current_document
		set formatted_source to do shell script "uncrustify -l OC -q -c ~/.uncrustify/uncrustify_obj_c.cfg -f " & current_document_path
		set text of current_document to formatted_source
	end repeat
end tell
The "uncrustify modified documents" service in Automator

Uncrustify Modified Documents

Open Xcode, find the new Services available in the “Xcode” menu. Use the Services Preferences to bind these Services to keyboard shortcuts to your liking.

The Xcode and Services menus

Services available in Xcode

Enjoy cleaner code.