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.
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
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.