Qt Creater中Clang-format的使用

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

 

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

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

 

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

这里仅以 ClangFormat 来讲明。插件

 

ClangFormat 是LLVM的一个子功能,LLVM是相似GCC的东西。3d

因此,想用 ClangFormat ,就须要下载LLVM,根据上面的地址,搜索适合本身的版本便可。我这里是win64位的。code

 

安装的时候PATH选项无所谓,由于Qt Creater的beautifier Clang Format  选项中既能够根据PATH搜索,也能够自行指定路径。orm

 

安装好LLVM以后,就能够设置 Clang Format 选项了。htm

先配置路径(如:C:\Program Files\LLVM\bin\clang-format.exe );blog

再选择代码样式,默认有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

相关文章
相关标签/搜索