使用Uncrustify在Xcode中格式化Objective-C代码

Xcode是开发iOS应用和Mac OS应用的必备工具,但这个工具的辅助功能相对于Eclipse之类的IDE来说,还是比较少,在Eclipse里只要按Ctrl+Shift+F,就可以将Java代码格式化得非常好看。而在Xcode里,只有Re-Indent(Ctrl+I)这一个调整缩进的功能,显然不够用。

如果想要完成完备的代码格式化,得要借助Uncrustify这样的工具。更进一步,我们用Automate配置一个针对Text的Service,再加上快捷键,就可以在Xcode里间接实现和Eclipse同样效果的代码格式化功能了。

首先安装Uncrustify工具。安装的方法很多,推荐用Homebrew来安装。如果机器上没有Homebrew,先用这条命令安装:

/usr/bin/ruby -e "$(curl -fksSL http://u.aodaren.com/homebrew)"

安装好Homebrew后,用这条命令安装Uncrustify:

brew install uncrustify

详细的Automate配置步骤可以参考这篇文章,如果不想自己配置,也可以直接下载已经配置好的workflow包,复制到~/Library/Services/,并解压就可以了:

mv Uncrustify-Objective-C.workflow.tar.gz ~/Library/Services/
cd ~/Library/Services/
tar zxvf Uncrustify-Objective-C.workflow.tar.gz

下载针对Objective-C语言的Uncrustify配置文件,移动到 ~/ 目录,并更名为 .uncrustify_obj_c.cfg,注意目标文件名前面有个 .:

mv uncrustify_obj_c.txt ~/.uncrustify_obj_c.cfg

如果上面已经顺利完成,那么现在到Xcode里选中一段代码,点右键,在Services里面应该已经有一个Uncrustify Objective-C服务了。选择后,即可将代码格式化。当然,如果每次都点鼠标显然太麻烦,下面来配置快捷键。

点屏幕左上角的苹果图标,选 System Preferences – Keyboard – Keyboard Shortcuts – Services,在Text分区里,找到刚添加的服务Uncrustify Objective-C,给这个服务加上快捷键。注意不要和Xcode里其它快捷键冲突,推荐设置为:Opt+Cmd+字母O。

这样以后在Xcode里,先用Cmd+A全选代码,再用Opt+Cmd+O来格式化代码。整个效果和Eclipse基本上差不多。

最后,如果对格式有不同的需求,还可以修改cfg文件里的设置,每个选项都有详细的说明,这里就不再赘述了。

4 thoughts on “使用Uncrustify在Xcode中格式化Objective-C代码

  1. Michael Veal’s “Starship Africa” examines dub music in the context of African culture and diaspora. The author examines various aspects of the sounds used in the production of dub music, which he claims have links to African expressions of memory, stress, nostalgia, and cultural identity. The author obviously believed in what he was selling, but could not sell me on his beliefs; high-minded examinations of sound in relevance to such phenomena as diaspora always strike me as being forced. Sometimes a cigar is just a cigar and an echo is just an echo.

    [回复]

  2. I seem to remember it was less than five years ago that Winston-Salem, or Forsyth County, paid Dell to set up there. If my memory is correct then I wonder how long the contract mandated that Dell stay there, and if they’ve bailed early if they have to return some of the dough.I get pretty sick of governments at any level entering bidding wars for jobs. Just keep taxes low and keep out of the way.  Miles_Teg

    [回复]

Leave a Reply

Your email address will not be published. Required fields are marked *