【问题标题】:Default working .clang-format file for Visual StudioVisual Studio 的默认工作 .clang 格式文件
【发布时间】:2021-05-08 19:59:10
【问题描述】:

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

YAML:87:19: 错误:未知键“IndentCaseBlocks”

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

编辑:当我编辑 .clang-format 文件时,某些键确实有效,例如TabIndentColumnLimit。我的版本是 VS 16.8.4。

【问题讨论】:

  • 您使用的是什么版本的 clang-format? Visual Studio 是否使用自己的 clang 格式?您是如何生成文件的?
  • @sweenish:我使用的是最新版本 (11.0)。更改选项中的默认样式确实有效(例如 LLVM、Google 等),但正如我所说 - 我想调整一些选项。我使用推荐的命令创建了文件:clang-format -style=llvm -dump-config > .clang-format。我已经尝试删除除TabWidth: 4 之外的所有键,这也可以。所以项目中的文件肯定是在加载中。

标签: c++ visual-studio clang-format


【解决方案1】:

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

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

然后,您可以右键单击该项目,添加一个新项目并选择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

【讨论】:

  • 感谢您的回复!在尝试此操作之前,我已经阅读了 Microsoft devblog 和 Clang 文档。它特别指出,如果将.clang-format 文件放在项目源代码树中,它将自动加载,并将覆盖Options 下设置的任何设置。当我想将样式应用于我的项目(Ctrl+K、Ctrl+D)时,似乎就是这种情况。您的参考配置文件也不适用于我。例如,我得到MaxEmptyLinesToKeep: 1 的“键值中的意外令牌”。但是,可以识别并应用 TabWidth: 4 等基本命令。
【解决方案2】:

好吧,自动创建的文件都不起作用,所以我决定手动检查所有键。事实证明,我担心的无效密钥并不多。以下是我必须注释掉以使 .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

我确实错过了一些选项,但总的来说我认为它看起来还不错。我希望这对将来的某人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-11
    • 2017-05-10
    • 2022-07-12
    • 1970-01-01
    • 2018-03-07
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    相关资源
    最近更新 更多