Qt Creater中Clang-format的使用

起因在于习惯性的想格式化代码,发现Qt Creater默认居然是没有代码格式化的,只有一个缩进,搞毛线啊!!!

搜索了下,倒是很容易就搜到了,Qt Creater中有个插件:beautifier,在 帮助-关于插件 中开启了即可(需要重启)。

可惜这只是一个接口,它的作用是调用格式化工具进行格式化。--这一点折腾了两个小时才意识到!惨痛的教训告诉我们,一定要看官方文档,别老想着走捷径!

按照官方的说法,它支持三种外部工具:Artistic Style、ClangFormat、Uncrustify 。并且都提供了下载地址。

这里仅以 ClangFormat 来说明。

ClangFormat 是LLVM的一个子功能,LLVM是类似GCC的东西。

所以,想用 ClangFormat ,就需要下载LLVM,根据上面的地址,搜索适合自己的版本即可。我这里是win64位的。

安装的时候PATH选项无所谓,因为Qt Creater的beautifier Clang Format  选项中既可以根据PATH搜索,也可以自行指定路径。

安装好LLVM之后,就可以设置 Clang Format 选项了。

先配置路径(如:C:Program FilesLLVMinclang-format.exe );

再选择代码样式,默认有LLVM、Google、Chromium、Mozilla、WebKit、File,此外还可以自定义。

默认样式,需要重点说一下File -- 因为其他的样式都是给定的样式,而 File 则不是。

File clang-format.exe -style=file 的意思,意味着 clang-format.exe 会去搜索样式文件( *.clang-format 文件)。

需要注意的是,它的搜索路径是当前文件所在的文件夹或者当前项目(不知道是否会继续往上层搜索--至少,工作空间就没验证成功)。

这样的话,它要求把 .clang-format 文件放在项目文件夹中,与我的习惯不符。

自定义样式

所幸,还有一个选择:Use customized style - add

如下

Value 部分内容如下

AccessModifierOffset: 0
AlignEscapedNewlinesLeft: false
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackParameters: false
BreakBeforeBinaryOperators: false
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
ColumnLimit: 128
BreakBeforeBraces: Attach
CommentPragmas: ''
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 0
ContinuationIndentWidth: 0
Cpp11BracedListStyle: false
DerivePointerBinding: false
IndentCaseLabels: true
IndentFunctionDeclarationAfterType: false
IndentWidth: 4
Language: Cpp
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
ObjCBlockIndentWidth: 4
PenaltyBreakBeforeFirstCallParameter: 100
PenaltyBreakComment: 100
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 100
PenaltyExcessCharacter: 1
PenaltyReturnTypeOnItsOwnLine: 20
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
TabWidth: 4
UseTab: Never

ps:上面这段配置是搜来的,忘了出处了~

使用

工具-Beautifier-ClangFormat 里面有两个选项,分别是格式化当前文件格式化选定内容

但是,这样使用很繁琐,很难用。所以最好给它设置一个快捷键,我的是ALT+CTRL+L(intellij的快捷键)。

注意,ClangFormat 有个特殊的选项 Format entire file if no text was selected ,建议选中这个选项,这样,只需要设置一个Format Selected Text 快捷键即可。

参考:

Beautifying Source Code

Clang-Format Style Options

原文地址:https://www.cnblogs.com/larryzeal/p/5617196.html