Automatic JUCE-like code formatting with clang-format

@reuk I love this format file! The only thing missing is the 3 spaces before the inheritance colon. Do you have any updates on that?

Awesome, thanks for sharing! Trying out AppCode instead of Xcode mainly because I’m sick of manual formatting, so this is a huge help!

For anyone using Xcode, it turns out there is an extension which can run clang-format inside Xcode. Go to Xcode menu > Xcode Extensions and purchase Xformat (it’s £2.99, money well spent!).

You can then open Xformat and File > Import the JUCE clang-format file, although it needs one tweak to match their version of clang-format (AlignOperands: true rather than Align, not sure what impact this has). I’ve attached the version I am using, based on @adamski’s with this one change.

To use it, you may need to enable the extension first in System Preferences > Extensions > Xcode Source Editor. You should then get a menu entry in Xcode: Editor > Xformat Extension > Reformat Using “JUCE” which will reformat your file. I’ve bound Cmd-S to this command so it auto formats when I hit Save (which I do by reflex in Xcode even though you don’t need to!)

The only slight issue I’ve found with it is when you reformat, the cursor resets to the top of the file, but your scroll position stays as it was so you just need to remember to click to reposition the cursor.

An alternative approach I explored was using Automator to invoke clang-format as a Service, which works but you need to first highlight all the text and you lose your scroll position; and also I tried running clang-format outside Xcode with a file watcher to trigger it, but this results in you losing your undo history when the file changes outside Xcode, so I think this is the best solution.

Personally I found AppCode really sluggish (on a top spec Macbook) and it would sometimes make my CPU go crazy at random (and I didn’t have the energy to debug why), so I’d rather make do with Xcode now that I can auto-format my C++ in it - the only feature I miss otherwise is more consistent autocomplete and “go to definition”, so if anyone knows how to improve this in Xcode I’m all ears!

clang-format.txt (2.0 KB)

5 Likes

Hey, I was trying to get this working, by following this post:

But xcode just deletes whatever code I have selected when I run the Quick Action via the Services menu.

Do you still use this approach?
what have you done in Automator that differs from the above link to get it working?
I’m on Xcode 12.4 currently.

I’m using a similar approach and wrote a blog post about it. The problem with all the 3rd party XCode extensions is that they either break on Xcode updates and/or contain their own clang-format binary that’s not updated as regularly as one would like.

https://www.apulsoft.ch/blog/clang-format-automator-quick-action/

1 Like

Another option, if you use CMake you can add a target that applies the formatting. I think that’s basically what this repo does.

2 Likes