Code formatting tool: clang-format

IDE: Visual Studio Code

Language: C/C++

Formatting tool: clang-format

Install

vscodeInstall the extension C/C++ , the extension will automatically install clang-format:

Configuration Preferences

  • Open preferences

    Shortcut keys: Command + ,

  • Search clang-format to configure

  • Configuration effective shortcut key

    • Full-text formatting of the current file

      Shift + option + F

    • Select block formatting

      Command + K

      Command + F

Configure formatting theme

Configuration item C_Cpp: Clang_format_fallback Style

  • Optional themes
    • Visual Studio
    • LLVM
    • Google
    • Chromium
    • Mozilla
    • WebKit
    • none
    • {key: value, …}
  • Reference for writing custom key-value
{ BasedOnStyle: Google, IndentWidth: 4, IndentCaseLabels: false, AccessModifierOffset: -4, AlignTrailingComments: true }
  • Common configuration items
# Language: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto
Language: Cpp

# Based on modifications on a certain theme
BasedOnStyle: Google

#Indent width
IndentWidth: 4

# Indent case tags
IndentCaseLabels: false

# Offset of access specifiers (public, private, etc.)
AccessModifierOffset: -4

#Limit of characters per line, 0 means no limit
ColumnLimit: 80

# Align consecutive trailing comments
AlignTrailingComments: true

# Allow all parameters of function declaration to be placed on the next line
AllowAllParametersOfDeclarationOnNextLine: false
# Allow short if statements to stay on the same line
AllowShortIfStatementsOnASingleLine: false
# Allow short case tags to be placed on the same line
AllowShortCaseLabelsOnASingleLine: true
# Allow short loops to stay on the same line
AllowShortLoopsOnASingleLine: false

# Allow sorting #include
SortIncludes: true

More configuration item reference:

  • VS Code C++ code formatting method (clang-format)
  • Clang-Format Style Options
Configure formatting form

Configuration item C_Cpp: Clang_format_style

The default is file, which will call the .clang-format file under the current project.

Note: This formatting configuration has a higher priority than the previous configuration!

Theme files can be generated through the clang-format tool, for example

# Execute if not installed
brew install clang-format

# Generate theme file
clang-format -style=Google -dump-config > .clang-format
Automatically format the configuration file when saving

When you press Command + S to save a file, or close editing of the current file, the automatic formatting code will be triggered.

Automatically format when ; is added at the end of the configuration line

Similar to Xcode, adding a semicolon after a statement will automatically trigger automatic formatting of the code.

Finally, here is the code formatting style I use:

{BasedOnStyle: Google, IndentWidth: 4, AccessModifierOffset: -4,AllowShortLoopsOnASingleLine: true,AllowShortIfStatementsOnASingleLine: true,AlignTrailingComments: true}
update:20.11.13
“C_Cpp.clang_format_fallbackStyle”: “{BasedOnStyle: Google, IndentWidth: 4, AccessModifierOffset: -4,AllowShortLoopsOnASingleLine: false,AllowShortIfStatementsOnASingleLine: true, AlignConsecutiveAssignments: true} “,

Custom style reference table

---
# Language: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto
Language: Cpp
# BasedOnStyle: LLVM
# Offset of access specifiers (public, private, etc.)
AccessModifierOffset: -2
# Alignment after opening brackets (opening round brackets, opening angle brackets, opening square brackets): Align, DontAlign, AlwaysBreak (always break after opening brackets)
AlignAfterOpenBracket: Align
# When assigning values continuously, align all equal signs
AlignConsecutiveAssignments: true
# When declaring consecutively, align all declared variable names
AlignConsecutiveDeclarations: true
 
AlignEscapedNewlines: Right
 
# Left-justify backslashes to escape newlines (use backslashes for newlines)
#AlignEscapedNewlinesLeft: true
# Horizontally align operands of binary and ternary expressions
AlignOperands: true
# Align consecutive trailing comments
AlignTrailingComments: true
 
# Allow all parameters of function declaration to be placed on the next line
AllowAllParametersOfDeclarationOnNextLine: false
# Allow short blocks to be placed on the same line
AllowShortBlocksOnASingleLine: true
# Allow short case tags to be placed on the same line
AllowShortCaseLabelsOnASingleLine: true
# 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: Empty
# Allow short if statements to stay on the same line
AllowShortIfStatementsOnASingleLine: false
# Allow short loops to stay on the same line
AllowShortLoopsOnASingleLine: false
 
#Always wrap after defining the return type (deprecated)
AlwaysBreakAfterDefinitionReturnType: None
#Always wrap after return type: None, All, TopLevel (top-level functions, functions not included in classes),
# AllDefinitions (all definitions, excluding declarations), TopLevelDefinitions (all top-level function definitions)
AlwaysBreakAfterReturnType: None
#Always wrap before multi-line string literals
AlwaysBreakBeforeMultilineStrings: false
#Always wrap after template declaration
AlwaysBreakTemplateDeclarations: false
# false means that the function parameters 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: false
# Braces break, only valid when BreakBeforeBraces is set to Custom
BraceWrapping:
  # After class definition
  AfterClass: false
  # After the control statement
  AfterControlStatement: false
  # Behind the enum definition
  AfterEnum: false
  # After the function definition
  AfterFunction: true
  # After the namespace definition
  AfterNamespace: false
  # Behind the ObjC definition
  AfterObjCDeclaration: false
  # Behind the struct definition
  AfterStruct: true
  #After union definition
  AfterUnion: true
 
  AfterExternBlock: false
  # before catch
  BeforeCatch: true
  # before else
  BeforeElse: true
  # Indent braces
  IndentBraces: false
  SplitEmptyFunction: true
  SplitEmptyRecord: true
  SplitEmptyNamespace: true
 
# Break before binary operators: None (break after operator), NonAssignment (break before non-assignment operator), All (break before operator)
BreakBeforeBinaryOperators: None
# Break before brace: Attach (always append the brace to the surrounding context), Linux (except function, namespace 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 wrap before braces), GNU (always wrap before braces and add extra indentation for control statement braces), WebKit (break before functions), Custom
# Note: Here it is considered that statement blocks also belong to functions
BreakBeforeBraces: Custom
# wrap before ternary operator
BreakBeforeTernaryOperators: false
 
# Wrap before the comma in the initialization list of the constructor
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
#Limit of characters per line, 0 means no limit
ColumnLimit: 80
# Regular expression describing a comment with special meaning that should not be split into multiple lines or otherwise altered
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
# The initialization lists of the constructors are either all on the same line, or they are all on their own line.
ConstructorInitializerAllOnOneLineOrOnePerLine: false
#Indentation width of initialization list of constructor
ConstructorInitializerIndentWidth: 4
# Indent width of continued lines
ContinuationIndentWidth: 4
# Remove spaces after braces { and before } in C++11 list initialization
Cpp11BracedListStyle: true
# Inherit the most commonly used alignment methods of pointers and references
DerivePointerAlignment: false
# Turn off formatting
DisableFormat: false
# Automatically detect whether function calls and definitions are formatted as one parameter per line (Experimental)
ExperimentalAutoDetectBinPacking: false
# Macros that need to be interpreted as foreach loops rather than function calls
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
# Sort #includes. #includes that match a certain regular expression have corresponding priorities. If they do not match, the default priority is INT_MAX (the smaller the priority, the higher the sorting).
#You can define a negative priority to ensure that some #includes are always at the top
IncludeCategories:
  - Regex: '^"(llvm|llvm-c|clang|clang-c)/'
    Priority: 2
  - Regex: '^(<|"(gtest|isl|json)/)'
    Priority: 3
  - Regex: '.*'
    Priority: 1
# Indent case tags
IndentCaseLabels: true
 
IndentPPDirectives: AfterHash
#Indent width
IndentWidth: 4
# When the function return type is wrapped, indent the function declaration or function name of the function definition.
IndentWrappedFunctionNames: false
# Keep the empty line at the beginning of the block
KeepEmptyLinesAtTheStartOfBlocks: false
# Regular expression for a macro that starts a block
MacroBlockBegin: ''
# Regular expression for a macro that ends a block
MacroBlockEnd: ''
#Maximum number of consecutive blank lines
MaxEmptyLinesToKeep: 1
# Namespace indentation: None, Inner (indent content in nested namespaces), All
NamespaceIndentation: Inner
# Indent width when using ObjC blocks
ObjCBlockIndentWidth: 4
# Add a space after ObjC's @property
ObjCSpaceAfterProperty: false
# Add a space before the ObjC protocol list
ObjCSpaceBeforeProtocolList: true
 
 
# Penalty for function call wrap after call(
PenaltyBreakBeforeFirstCallParameter: 19
#Introduce newline penalty in a comment
PenaltyBreakComment: 300
# Penalty for the first line break before <<
PenaltyBreakFirstLessLess: 120
#Introduce newline penalty in a string literal
PenaltyBreakString: 1000
# Penalty for each character outside the line character limit
PenaltyExcessCharacter: 1000000
# Put the function's return type into its own row's penalty
PenaltyReturnTypeOnItsOwnLine: 60
 
# Alignment of pointers and references: Left, Right, Middle
PointerAlignment: Left
# Allow comments to be re-formatted
ReflowComments: true
# Allow sorting #include
SortIncludes: true
 
# Add spaces after C-style casts
SpaceAfterCStyleCast: false
 
SpaceAfterTemplateKeyword: true
 
# Add spaces before assignment operators
SpaceBeforeAssignmentOperators: true
# Add a space before the opening parenthesis: Never, ControlStatements, Always
SpaceBeforeParens: ControlStatements
# Add spaces between empty parentheses
SpaceInEmptyParentheses: false
# Number of spaces to add before trailing comments (only applies to //)
SpacesBeforeTrailingComments: 2
# Add spaces after < and before > in angle brackets
SpacesInAngles: false
# Add spaces to container (ObjC and JavaScript arrays and dictionaries, etc.) literals
SpacesInContainerLiterals: false
# Add spaces between brackets for C-style type conversions
SpacesInCStyleCastParentheses: false
# Add spaces after (and before) parentheses
SpacesInParentheses: false
# Add spaces after [and] before square brackets. Lambda expressions and declarations of unspecified arrays are not affected.
SpacesInSquareBrackets: false
# Standard: Cpp03, Cpp11, Auto
Standard: Cpp11
#tab width
TabWidth: 4
# Use tab characters: Never, ForIndentation, ForContinuationAndIndentation, Always
UseTab: Never