一. 前言

使用Xcode IDE进行C++/swift相关代码的编写,系统默认的 ctri + i 快捷键格式化代码功能有限,只能处理缩进,无法处理语句中的空格等。对于C++,建议安装clang-format插件。对于Swift,建议安装XCFormat实现代码的美化功能。

二. 安装

clang-format 安装过程

1
2
3
4
5
6
7
8
# 安装 clang-format
brew install clang-format

# 查看安装的版本
clang-format --version

# 查看安装位置(重要)
whereis clang-format # 我的输出:clang-format: /opt/homebrew/bin/clang-format

XCFormat 安装过程

打开Xcode,在菜单中进入Xcode Extensions,找到XCFormat进行安装。

XCFormat安装完成后,直接看本文第四部分即可。

三. clang-format配置

cmd+空格键,搜索Automator.app,进入自动操作应用:

自动操作配置界面

脚本内容如下:

1
2
export PATH=/opt/homebrew/bin:$PATH
clang-format

要注意,PATH的路径要根据clang-format的安装位置进行修改(很多网络教程没有说清楚这一点),第二部分已经介绍如何查看安装位置。保存名字为xcode_format,然后点击右上角的运行,若成功会在下方显示:工作流程已完成。

随后,配置.clang-format文件:

1
touch ~/.clang-format

文件内容示例如下(具体配置项参考 https://clang.llvm.org/docs/ClangFormatStyleOptions.html ):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
BasedOnStyle: LLVM
# 缩进
IndentWidth: 4
ColumnLimit: 0
# 最多的空行
MaxEmptyLinesToKeep: 1
AlignTrailingComments: true
AllowShortIfStatementsOnASingleLine: false
ObjCSpaceAfterProperty: true
ObjCBlockIndentWidth: 4
AllowShortBlocksOnASingleLine: false
BraceWrapping:
AfterControlStatement: true
AfterObjCDeclaration: false
KeepEmptyLinesAtTheStartOfBlocks: false
AllowShortFunctionsOnASingleLine: true
BinPackArguments: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
IndentWrappedFunctionNames: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
AllowShortCaseLabelsOnASingleLine: false
# switch case 缩进
IndentCaseLabels: true

现在整个配置就完成了,在Xcode中选中代码后,右键 -> Services -> xcode_format。

四. 快捷键

clang-format

打开设置 -> 键盘 -> 快捷键,左侧点击App快捷键,然后点加号。

选择应用程序为Xcode,菜单标题为xcode_format(根据你之前保存的名字),快捷键输入ctrl+i。

XCFormat

同上,菜单标题为 Format Active FileFormat Selected Lines,并输入不冲突的快捷键即可。

前者会格式化当前所在文件全部代码,后者格式化选中代码。