Sep 20, 2010

Xcode + AStyle

Anar here...

You know, I think there are many people, who find the auto-formatting of source code in Xcode is really terrible :( I mean, it is very weak (in terms of configuration) for such a descent development environment, which XCode actually is.

Since a very long time I use AStyle (Artistic Style) to format my code. It actually does remarkable job and it is an extremely tunable tool. You can adjust it almost for all, if not for all, indentations schemas...

I have already posted a long time ago a recipe of how to setup astyle for eclipse. Now, it is time to use it in XCode.

I use a user script menu to add my own script, which will than trigger the astyle command to format a source code for me.

Use the User Script menu to add a new script. You should add your script to a section "Text", the type of the script should - a shell script.
Next is the properties of the script:
Input: Entire Document
Directory: Selection
Output: Replace Document Contents
Errors: Display in Alert

And the content of the script:

#!/bin/bash

# I pass selected file instead of a selection, because astyle 1.24
# fails to parse struct with access modifiers. It just hangs instead.
# I also use a tmp file in order to avoid annoying Xcode message, that
# source file was changed outside of Xcode.

# Important: there must be always a new line at the end of the source file.
# Next time I provide a fix for that.


TMP=`mktemp -t xcode.XXXXXXXXXX` || exit 1

cat << 'EOFEOFEOF' > "$TMP"
%%%{PBXAllText}%%%EOFEOFEOF

astyle --options=<***PATH_TO_YOUR_ASTYLE_RC_FILE***> $TMP &>/dev/null

echo -n "%%%{PBXSelection}%%%"
cat $TMP
echo -n "%%%{PBXSelection}%%%"

rm $TMP

Restriction: Be advised, there must be always a new line at the end of the source file!

BTW, don't forget to change that <***PATH_TO_YOUR_ASTYLE_RC_FILE***> to a real path to your astyle resource file ;)

The script above is actually a second version of my script. The first one was much simpler:

#!/bin/sh

echo -n "%%%{PBXSelection}%%%"
/usr/bin/astyle --options=<***PATH_TO_YOUR_ASTYLE_RC_FILE***> <&0 echo -n "%%%{PBXSelection}%%%"
But this version didn't work for me with astyle 1.24. This is why in the second version of the script:
I pass selected file instead of a selection, because astyle 1.24 fails to parse struct with access modifiers. It just hangs instead. I also use a tmp file in order to avoid annoying Xcode message, that source file was changed outside of Xcode.
Finally, just assign some shortcuts (I prefer Options + Command + L) to you script and voilĂ ...

No comments: