Xcode 自带的代码格式化功能( control + I )很有限,其 “格式化” 仅限于设置缩进,代码里面的格式是不会处理的。所以需要借助额外的工具来完成代码的美化。
clang-format 便是可选的工具之一,它可用来格式化 C/C++/Java/JavaScript/Objective-C/Protobuf/C# 等代码。
其内置了多种预设的代码风格,分别有 LLVM, Google, Chromium, Mozilla, WebKit。
可通过添加 .clang-format
文件来进行配置。优先使用项目中的 .clang-format
文件,然后会查找系统中存在的 .clang-format
文件。
一个配置文件的示例:
BasedOnStyle: LLVM IndentWidth: 4
所有可用的配置参数可在其 文档 Clang-Format Style Options 中查看。一般指定一个喜欢的预设风格即可。
clang-format 的安装
$ brew install clang-format
检查安装:
$ clang-format --version clang-format version 8.0.0 (tags/google/stable/2019-01-18)
虽然安装好了,但它是命令行工具,要在 Xcode 中使用,还需要借助 macOS 自带的