Nat! bio photo

Nat!

Senior Mull.

Twitter RSS

Github

Sorting and Beautifying Code in Xcode

Thanks to Automator it's very easy to create a Service using Applescript and unix commands. Here's an example how to sort lines in Xcode with the context menu.

In Automator create a new Service (Dienst)

Automator Open Dialog

Then add a shell script to the Service (red). Be sure to check the box (yellow) and change the command to sort (green), Finally save the script. The name you give to your script, will be the name that appears in the Services menu. I chose "Zeilen sortieren".

Add

Now in 10.8.1 everything works fine. But I remember that in former times, it may have been necessary to do some magic to get the service going (login/logut). But maybe I am confusing this with Colorsync or Finder plugins.

Anyway... In Xcode select some lines and run your "Service" on it. If you don't have many services, you might be lucky, and the services will appear directly in the top menu.

Doing the magic in Xcode

Now with these preliminaries out of the way, I have created a small unix tool, that aligns variables (and as a bonus also can align assignment statements).  So this:

   int    foo;
   static char  *x;
   auto volatile int  foo[ 126];

becomes

   int                 foo;
   static char         *x;
   auto volatile int   foo[ 126];

and

   x = foo
    // bla
      y[x] = bar

becomes

   x     = foo
    // bla
   y[x]  = bar

4 Comments

A photo of Ssp

From: Ssp

Are you aware of the ThisService utility?

It gives you a way to wrap scripts up in a service without having to submit yourself to the clumsy Automator.

http://wafflesoftware.net/thisservice/

And, yes, the Services Menu required a logout to be re-built in the early days of OS X, there was a special API call for the purpose as well. I think automatic rebuilding came around X.4 or X.5. The OS will only allow the Services of applications which have been used before to appear (for security reasons, I guess).

A photo of Nat!

From: Nat!

I am not sure I would call the method using Automator clumsy. After all I can create and test a new service like my example with "sort" in less than a minute.

A photo of Ssp

From: Ssp

I’m afraid I cannot help but find Automator (the application, not your way of using it) as clumsy.

A photo of sort xcode

From: sort xcode

Nice automation tricks. For Xcode 8 there's an extension now to sort lines, please try it out when you switch to 8: http://apps.brrm.ru/xcsort/

Post a comment

All comments are held for moderation; basic HTML formatting accepted.

Name:
E-mail: (not published)
Website: