Visual Studio 的默认工作 .clang 格式文件

Default working .clang-format file for Visual Studio

我想在 Visual Studio 2019(不是代码)中使用 Clang C++ 语法并进行一些修改。我创建了一个 .clang 格式的文件并将其复制到我的项目中。 Visual Studio 可以识别该文件,但会提示我一大堆无法识别的密钥(例如

YAML:87:19: error: unknown key 'IndentCaseBlocks'

)。 Visual Studio 是否有推荐的默认文件,其中包含代表标准格式的最大受支持(可能推荐)设置?

编辑: 当我编辑 .clang-format 文件时,有些键可以使用,例如TabIndentColumnLimit。我的版本是VS 16.8.4.

您的 clang 文件内容似乎有问题。您可以访问clang的官方网站了解更多信息。

首先,您需要检查Tools->Options->Text Editor->C/C++->Formatting->General->Enable ClangFormat support。你也可以 Use custom clang-format.exe file.

然后,您可以右键单击该项目,添加一个新项目并select Formatting->Clang Format file。所以你可以在里面添加你想要的东西。

这里是参考配置文件:

BasedOnStyle: Google
Language: Cpp
ColumnLimit: 120

BraceWrapping:
 # class definition behind
 AfterClass: false
 # After the control statement
 AfterControlStatement: false
 # enum definition behind
 AfterEnum: true
 # After the function definition
 AfterFunction: false
 # After the namespace definition
 AfterNamespace: false
 # ObjC definition behind
 AfterObjCDeclaration: false
 # struct definition behind
 AfterStruct: false
 # union definition
 AfterUnion: false
 #ExternBlock definition behind
 AfterExternBlock: false
 # before catch
 BeforeCatch: false
 # else before
 BeforeElse: false
 # Indented braces
 IndentBraces: false
 # Split empty function
 SplitEmptyFunction: true
 # Split empty records
 SplitEmptyRecord: true
 # Split empty namespace
 SplitEmptyNamespace: true

# Add a space after @property, \@property (readonly) instead of \@property(readonly).
ObjCSpaceAfterProperty: true
# Offset of access specifiers (public, private, etc.)
AccessModifierOffset: -4
# Alignment after opening brackets (opening parentheses, opening angle brackets, opening square brackets): Align, DontAlign, AlwaysBreak (always wrap after opening brackets)
AlignAfterOpenBracket: Align
# When assigning consecutively, align all equal signs
AlignConsecutiveAssignments: false
# When consecutive declarations, align all declared variable names
AlignConsecutiveDeclarations: false
# Left align backslashes that escape newlines (use backslashes for newlines)
AlignEscapedNewlinesLeft: true
# Align the operands of binary and ternary expressions horizontally
AlignOperands: true
# Align consecutive trailing comments
AlignTrailingComments: true
# Allow all parameters of the function declaration to be placed on the next line
AllowAllParametersOfDeclarationOnNextLine: true
# Allow short blocks on the same line
AllowShortBlocksOnASingleLine: false
# Allow short case labels on the same line
AllowShortCaseLabelsOnASingleLine: false
# Allow short functions to be placed on the same line: None, InlineOnly (defined in the class), Empty (empty function), Inline (defined in the class, empty function), All
AllowShortFunctionsOnASingleLine: None
# Allow short if statements to stay on the same line
AllowShortIfStatementsOnASingleLine: false
# Allow short loops to stay on the same line
AllowShortLoopsOnASingleLine: false
# Always break after defining the return type (deprecated)
AlwaysBreakAfterDefinitionReturnType: None
# Always wrap after the return type: None, All, TopLevel (top functions, functions not included in the class),
# AllDefinitions (all definitions, excluding declarations), TopLevelDefinitions (the definitions of all top-level functions)
AlwaysBreakAfterReturnType: None
# Always wrap before multi-line string literal
AlwaysBreakBeforeMultilineStrings: false
# Always wrap after the template statement
AlwaysBreakTemplateDeclarations: false
# false means that the function arguments are either on the same line or on their own line
BinPackArguments: true
# false means that all formal parameters are either on the same line or on their own line
BinPackParameters: true
# Braces wrap, only valid when BreakBeforeBraces is set to Custom
# Newline before binary operators: None (newline after the operator), NonAssignment (newline before the non-assignment operator), All (newline before the operator)
BreakBeforeBinaryOperators: NonAssignment
# Wrap a line before the brace: Attach (always attach the brace to the surrounding context), Linux (except for functions, namespaces and class definitions, similar to Attach),
# Mozilla (except enumeration, function, record definition, similar to Attach), Stroustrup (except function definition, catch, else, similar to Attach),
# Allman (always break before the curly brace), GNU (always break before the curly brace, and add extra indentation to the curly brace of the control statement), WebKit (newline before the function), Custom
# Note: It is considered that the statement block also belongs to the function
BreakBeforeBraces: Custom
# Break before ternary operator
BreakBeforeTernaryOperators: true
# Break before the comma in the initialization list of the constructor
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
# Describe the regular expression of the comment with special meaning, it should not be divided into multiple lines or changed in other ways
CommentPragmas:'^ IWYU pragma:'
# The initialization list of the constructor is either all on the same line or on their own line
ConstructorInitializerAllOnOneLineOrOnePerLine: true
# The comfort list of constructors all wrap
AllowAllConstructorInitializersOnNextLine: false
# The indentation width of the initialization list of the constructor
ConstructorInitializerIndentWidth: 4
# The indentation width of the continued line
ContinuationIndentWidth: 4
# Remove the space before the curly braces {after and before the C++11 list initialization
Cpp11BracedListStyle: true
# Inherit the most commonly used pointer and reference alignment
DerivePointerAlignment: false
# Turn off formatting
DisableFormat: false
# Automatically detect whether the function call and definition are formatted as one parameter per line (Experimental)
ExperimentalAutoDetectBinPacking: false
# Fix namespace comment
FixNamespaceComments: true
# Need to be interpreted as a foreach loop instead of a function call macro
ForEachMacros:
 -foreach
 -Q_FOREACH
 -BOOST_FOREACH
# Sort #include, #include that matches a regular expression has a corresponding priority, and the default priority is INT_MAX (the smaller the priority, the higher the priority),
# You can define a negative priority to ensure that certain #include is always at the top
IncludeCategories:
 -Regex:'^<ext/.*\.h>'
   Priority: 2
 -Regex:'^<.*\.h>'
   Priority: 1
 -Regex:'^<.*'
   Priority: 2
 -Regex:'.*'
   Priority: 3

IncludeIsMainRegex:'([-_](test|unittest))?$'
# Indent case label
IndentCaseLabels: true
# Indentation width
IndentWidth: 4
# When the function return type wraps, indent the function declaration or the function name of the function definition
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
# Keep the blank line at the beginning of the block
KeepEmptyLinesAtTheStartOfBlocks: true
# The regular expression of a macro to start a block
MacroBlockBegin:''
# End the regular expression of a block macro
MacroBlockEnd:''
# Maximum number of consecutive blank lines
MaxEmptyLinesToKeep: 1
# Namespace indentation: None, Inner (indent the content in the nested namespace), All
NamespaceIndentation: None
# Indent width when using ObjC block
ObjCBlockIndentWidth: 4
# Add a space before ObjC's protocol list
ObjCSpaceBeforeProtocolList: false
# Penalty that wraps the function call after call(
PenaltyBreakBeforeFirstCallParameter: 19
# Introduce a penalty for line breaks in a comment
PenaltyBreakComment: 300
# The penalty for the first line break before <<
PenaltyBreakFirstLessLess: 120
# Introduce a penalty for line breaks in a string literal
PenaltyBreakString: 1000
# Penalty for each character outside the line character limit
PenaltyExcessCharacter: 1000000
# Put the return type of the function in the penalty of its own line
PenaltyReturnTypeOnItsOwnLine: 60
# Alignment of pointer and reference: Left, Right, Middle
PointerAlignment: Left
RawStringFormats:
 -Language: Cpp
   Delimiters:
     -cc
     -CC
     -cpp
     -Cpp
     -CPP
     -'c++'
     -'C++'
   CanonicalDelimiter:''
   BasedOnStyle: google
 -Language: TextProto
   Delimiters:
     -pb
     -PB
     -proto
     -PROTO
   EnclosingFunctions:
     -EqualsProto
     -EquivToProto
     -PARSE_PARTIAL_TEXT_PROTO
     -PARSE_TEST_PROTO
     -PARSE_TEXT_PROTO
     -ParseTextOrDie
     -ParseTextProtoOrDie
   CanonicalDelimiter:''
   BasedOnStyle: google
# Allow retypesetting comments
ReflowComments: true
# Allow sorting#include
SortIncludes: true
SortUsingDeclarations: true
# Add space after C style type conversion
SpaceAfterCStyleCast: false
# Add a space before the assignment operator
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
# Add a space before opening the parentheses: Never, ControlStatements, Always
SpaceBeforeParens: ControlStatements
# Add spaces in empty parentheses
SpaceInEmptyParentheses: false
# The number of spaces added before trailing comments (only applicable to //)
SpacesBeforeTrailingComments: 2
# Add spaces before and after the angle brackets
SpacesInAngles: false
# Add spaces in the literal of the container (ObjC and JavaScript arrays and dictionaries, etc.)
SpacesInContainerLiterals: true
# Add spaces in the brackets of C-style type conversion
SpacesInCStyleCastParentheses: false
# Add a space before the (after and) of the parentheses
SpacesInParentheses: false
# Add a space before the [after and] of the square brackets, the declaration of lamda expressions and arrays of unspecified size will not be affected
SpacesInSquareBrackets: false
# Standard: Cpp03, Cpp11, Auto
Standard: Cpp11
# tab width
TabWidth: 4
# Use tab characters: Never, ForIndentation, ForContinuationAndIndentation, Always
UseTab: Never

好的,none 个自动创建的文件有效,所以我决定毕竟手动完成所有密钥。事实证明,并没有我担心的那么多无效密钥。这是我必须注释掉的键列表,以便 .clang-format 在 Visual Studio 2019 中工作:

# AlignConsecutiveBitFields: false
# AlignOperands:   Align
# AllowShortEnumsOnASingleLine: true
#  BeforeLambdaBody: false
#  BeforeWhile:     false
# IndentCaseBlocks: false
# IndentExternBlock: AfterExternBlock
# InsertTrailingCommas: None
# ObjCBreakBeforeNestedBlockParam: true
# WhitespaceSensitiveMacros:
#  - STRINGIZE
#  - PP_STRINGIZE
#  - BOOST_PP_STRINGIZE

有几个选项我确实错过了,但总的来说我认为它看起来还不错。我希望这对以后的人有所帮助。