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.


#1
Run Automator. Start a new service workflow.

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

#3
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.
mode=c
# ANSI style formatting/indenting
style=ansi
# Do not retain a backup of the original file
suffix=none
# Indent 'class' and 'struct' blocks so that the blocks 'public:', 'protected:' and 'private:' are indented.
indent-classes
# Indent 'switch' blocks so that the 'case X:' statements are indented in the switch block.
indent-switches
# Indent 'case X:' blocks from the 'case X:' headers.
indent-cases
# Add extra indentation to namespace blocks.
indent-namespaces
# Indent multi-line preprocessor definitions ending with a backslash.
indent-preprocessor
# Converts tabs into single spaces.
convert-tabs
# Set the minimal indent that is added when a header is built of multiple-lines.
min-conditional-indent=0
# Indent a maximum of # spaces in a continuous statement
max-instatement-indent=80
# Insert space padding around operators.
pad=oper
# Insert space padding around parenthesis on the inside only. 
pad=paren-in
# Remove extra space padding around parenthesis on the inside and outside.
unpad=paren


Drawbacks

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:

http://www.youtu.be/d8bbE6_OHGc

Best,
Gabriel