Mar 23, 2011

Xcode + AStyle. Part 2. (for Xcode 4.x)

Anar here...

Long time ago I've described a recipe to use astyle from within Xcode 3.x.

Now as you may know, Xcode 4 doesn't provide the "user script" menu. I knew about it since Xcode 4 developer preview versions, but kept hoping the menu item would be back.
This didn't happen :( We have now a stable release of Xcode 4 and there is no sign of user's script in it.

What I think is that Apple either couldn't implement a support for "user script" or they want us to use automator services.
So, now I try to use automator to accomplish the same as I did in XCode 3's user script menu.

Run Automator. Start a new service workflow.

Select, that you service will receives selected "text" and check that it will "Replace selected text"

Drag the "Run Shell Scrip" to your workflow and add commands as in the following screenshot:

Save your service and now when you want to re-indent your code, just select the whole source file content and select your service from the service menu. Works OK, but there are some drawbacks, see below (at the very end of the post).

Of course you must write the path to your own astyle option file, in my case I use "/Users/anar/Documents/workspace/Support/astylerc", as you can see on the screenshot, which sets the following:
#Indent a C or C++ file.
# ANSI style formatting/indenting
# Do not retain a backup of the original file
# Indent 'class' and 'struct' blocks so that the blocks 'public:', 'protected:' and 'private:' are indented.
# Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block.
# Indent 'case X:' blocks from the 'case X:' headers.
# Add extra indentation to namespace blocks.
# Indent multi-line preprocessor definitions ending with a backslash.
# Converts tabs into single spaces.
# Set the minimal indent that is added when a header is built of multiple-lines.
# Indent a maximum of # spaces in a continuous statement
# Insert space padding around operators.
# Insert space padding around parenthesis on the inside only. 
# Remove extra space padding around parenthesis on the inside and outside.


The following is the only, what I found so far:

  • Unfortunately I don't see any way to keep the potision of the cursor after the service is called.
  • One should select the whole file content and execute the service on it. Which is inconvenient in some cases. I didn't find a way to get a file name of the current file, which I could then provide to the service.

1 comment:

Gabriel Gatzsche said...

Many thanks for this great tutorial. Its so useful to me that I have created a video tutorial: