VSCode installation and usage of clang-format plug-in
- 1. clang-format plug-in installation
- 2. Install the real formatting tool clang-format
- 3. Generate .clang-format configuration file and modify it
- 4. Modify configuration file
-
- 4.1 Global configuration file modification
- 4.2 Modification of workspace configuration file
- 5. Format code
1.clang-format plug-in installation
Plug-in installation methods are divided into two types: direct installation and offline installation.
Direct installation: Search clang-format in the VSCode extension and install the top-ranked plug-in;
Offline installation: Link: Search clang-format in the VSCode plug-in store, select the most downloaded plug-in, click to download the offline package, and then install the offline package in VSCode.
Download the plug-in installation package:
Install offline package in VSCode:
2. Install the real formatting tool clang-format
- Linux system installation: use the command
sudo apt install clang-format
; - Windows system installation: This tool is integrated in the tool package LLVM. Download the latest .exe package and install it after the download is complete. clang-format.exe can be found in the
bin
folder of the installation directory.
3. Generate and modify the .clang-format configuration file
Generate .clang-format configuration file command:
clang-format --style=LLVM --dump-config > ./.clang-format
The following customization based on LLVM style:
--- BasedOnStyle: LLVM Language: Cpp # this style configuration is based on google style configuration. # The following configuration is different from the basic configuration. #Indent width IndentWidth: 4 # Offset of access permission specifiers (public/private, etc.) AccessModifierOffset: -4 # # Alignment after opening brackets (opening parentheses, angle brackets, 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 # Alignment of backslash bar line breaks # -- DontAlign - Do not align # -- Left - Backslashes are aligned to the left # -- Right - Backslashes are aligned to the right #AlignEscapedNewlines: Right #Alignment of binary and ternary expressions (when the expression needs to occupy multiple lines) # -- DontAlign - Do not align # -- Align - Align starting from operator # -- AlignAfterOperator - Align starting from the operand AlignOperands: true # # Whether to align end-of-line comments AlignTrailingComments: true # # All parameters declared by the function are placed on the next line # AllowAllParametersOfDeclarationOnNextLine: false # # Whether to allow short code blocks to be placed on the same line # AllowShortBlocksOnASingleLine: false # # Put short case labels and statements on the same line # AllowShortCaseLabelsOnASingleLine: true # # Put short functions on the same line # -- None - don't put short functions on the same line # -- InlineOnly - Only inline functions within the class are placed on the same line, and global empty functions are not placed on the same line. # -- Empty - only put empty functions on the same line # -- Inline - Put the inline functions in the class on the same line, but not the global empty functions on the same line. # -- All - all allowed on the same line AllowShortFunctionsOnASingleLine: InlineOnly # # Keep short if statements on the same line # AllowShortIfStatementsOnASingleLine: true # # Keep short loops on the same line # AllowShortLoopsOnASingleLine: true # # Always wrap after the return type: None, All, TopLevel (top-level functions, functions not included in the class), # # AllDefinitions (all definitions, excluding declarations), TopLevelDefinitions (all top-level function definitions) #AlwaysBreakAfterReturnType: None # #Always wrap before multi-line string literals #AlwaysBreakBeforeMultilineStrings: true # #Always wrap after template declaration AlwaysBreakTemplateDeclarations: true # # Parameter placement rules when calling a function # -- false - Parameters must either be placed on the same line, or each parameter may occupy its own line # -- true - no mandatory requirement # BinPackArguments: true # Parameter placement rules when declaring and defining functions # -- false - Parameters must either be placed on the same line, or each parameter may occupy its own line # -- true - no mandatory requirement # BinPackParameters: true # Braces placement style # -- Attach - the curly braces follow the preceding content and are placed on the same line # -- Linux - Similar to Attach, except that the braces for functions, namespaces, and class definitions are placed on the next line # -- Mozilla - Similar to Attach, except that the curly braces for enumerations, functions, and structures (class\struct\union) are placed on the next line # -- Stroustrup - Similar to Attach, but the "{}" before the function definition, before catch, and before else are placed on a separate line # -- Allman - always wrap # -- Whitesmiths - Like Allman, but "{}" is aligned to the same position as the inner statements # -- GNU - always wrap, but "{}" after a control statement is always aligned to the next position # -- WebKit - similar to Attach, but wrap before function definition # -- Custom - depends on BraceWrapping # Note: Here it is considered that statement blocks also belong to functions BreakBeforeBraces: Custom # Braces break, only valid when BreakBeforeBraces is set to Custom BraceWrapping: # After class definition AfterClass: true # After the control statement AfterControlStatement: true # Behind the enum definition AfterEnum: true # After the function definition AfterFunction: true # After the namespace definition AfterNamespace: true # Behind the ObjC definition AfterObjCDeclaration: true # Behind the struct definition AfterStruct: true #After union definition AfterUnion: true # after extern AfterExternBlock: true # before catch BeforeCatch: true # before else BeforeElse: true # Continue to indent the braces IndentBraces: false # Separate empty functions # # Whether to split the function body when the "{}" of the blank function and the function name do not need to be placed on the same line SplitEmptyFunction: true # Separate empty statements # # When the "{}" of a blank structure (class\struct\union) needs to be placed on a separate line, whether to split the "{}" SplitEmptyRecord: true # Detach empty namespace # # When the "{}" of a blank namespace needs to be placed on a separate line, whether to split the "{}" SplitEmptyNamespace: true # # Wrap before binary operators: None (wrap after operator), NonAssignment (wrap before non-assignment operator), All (wrap before operator) BreakBeforeBinaryOperators: NonAssignment # BreakBeforeInheritanceComma: false # #Newline before ternary operator # When ternary expressions cannot be placed on the same line, whether to wrap before the ternary operator # -- true - operator is at the beginning of a new line # -- false - operator is at the end of the previous line BreakBeforeTernaryOperators: true # BreakConstructorInitializersBeforeComma: false # # Constructor initialization list splitting method # -- BeforeColon - split before colon ':', colon is at the beginning of the line, comma ',' is at the end of the line # -- BeforeComma - split before colon and comma, colon and comma are at the beginning of the line, and aligned # -- AfterColon - Split after colon and comma, which are at the end of the line BreakConstructorInitializers: BeforeColon # # Whether to wrap a new line after each java annotation # BreakAfterJavaFieldAnnotations: false # # Whether to split a string that is too long # BreakStringLiterals: false # #Limit on the character length of each line, 0 means no limit ColumnLimit: 0 # # Regular expression used to match comment information. The matched lines will not be modified in any way. # CommentPragmas: '^ IWYU pragma:' # Whether to compress the following namespace # -- true - put following namespaces on the same line # -- false - each namespace is on a new line CompactNamespaces: false # # The initialization lists of the constructors are either all on the same line, or they are all on their own line. # -- true - put initialization lists on the same line if possible; if length selection is not met, put each on its own line # -- false - the initialization list can be placed arbitrarily # ConstructorInitializerAllOnOneLineOrOnePerLine: false # # Alignment width of constructor initialization list and base class integration list ConstructorInitializerIndentWidth: 4 # # Alignment width of continuation statement ContinuationIndentWidth: 4 # # Remove spaces after curly brackets {<!-- --> and before } in C++11 list initialization Cpp11BracedListStyle: true # Whether to automatically analyze pointer alignment # -- true - Automatically analyze and use pointer alignment. If it cannot be analyzed, use PointerAlignment. # -- false - no automatic analysis # DerivePointerAlignment: true # Whether to disable formatting DisableFormat: false # ExperimentalAutoDetectBinPacking: false # Whether to automatically correct the closing comment of the namespace # -- true - Automatically add or modify incorrect namespace closing comments at the end of short namespaces # -- false - no automatic correction FixNamespaceComments: true # foreach loop ForEachMacros: -foreach - Q_FOREACH - BOOST_FOREACH # Grouping rules for sorting multiple include blocks (includes separated by blank lines) # -- Preserve - Preserve the original block separation and sort them individually # -- Merge - Treat all chunks as one and sort them # -- Regroup - Sort all blocks as one, and then group them according to the rules of IncludeCategories IncludeBlocks: Preserve # IncludeCategories: # - Regex: '^<ext/.*\.h>' # Priority: 2 # - Regex: '^<.*\.h>' # Priority: 1 # - Regex: '^<.*' # Priority: 2 # - Regex: '.*' # Priority: 3 # IncludeIsMainRegex: '([-_](test|unittest))?$' # # Indent case tags # -- true - case is not aligned with switch # -- false - case and switch aligned IndentCaseLabels: false # Indentation rules for preprocessing commands (#if\#ifdef\#endif, etc.) # -- None - no indentation # -- AfterHash - indent after the leading '#', '#' is placed on the far left, and subsequent statements participate in indentation # -- BeforeHash - indent before leading '#' IndentPPDirectives: AfterHash # # When the function return type is wrapped, indent the function declaration or function name of the function definition. #IndentWrappedFunctionNames: false # String quoting rules in JavaScript # -- Leave - Leave it as is # -- Single - Use single quotes for everything # -- Double - use double quotes for everything JavaScriptQuotes: Leave #Whether to wrap the line after the JavaScript import/export statement # JavaScriptWrapImports: true # # Preserve the empty line at the beginning of the block # -- true - keep empty lines at the beginning of blocks # -- false - remove empty lines at the beginning of the block KeepEmptyLinesAtTheStartOfBlocks: true # Regular expression used to identify the start of macro-defined blocks # MacroBlockBegin: '' # Regular expression used to identify the end of macro-defined blocks # MacroBlockEnd: '' # # Maximum number of consecutive blank lines MaxEmptyLinesToKeep: 1 # #Indentation rules within namespaces # -- None - neither indented # -- Inner - Indent only nested namespace contents # -- All - Indent all namespace content NamespaceIndentation: None #Objective-C related configuration # ObjCBlockIndentWidth: 2 # ObjCSpaceAfterProperty: false # ObjCSpaceBeforeProtocolList: false #PenaltyBreakAssignment: 2 # PenaltyBreakBeforeFirstCallParameter: 1 #PenaltyBreakComment: 300 #PenaltyBreakFirstLessLess: 120 # PenaltyBreakString: 1000 # PenaltyExcessCharacter: 1000000 # PenaltyReturnTypeOnItsOwnLine: 200 # # Alignment rules for pointers and references (* and & amp;) # -- Left - * Near the left # -- Right - * Near the right # -- Middle - * Place in the middle # NOTE: In SpaceAroundPointerQualifiers is Default, # And enabled after DerivePointerAlignment expires PointerAlignment: Right # RawStringFormats: # - Delimiter: pb # Language: TextProto # BasedOnStyle: google # #Reformat comments ReflowComments: false # # Reorder #include # -- Never - do not sort # -- CaseSensitive - sorting is case sensitive # -- CaseInsensitive - Sorting is case-insensitive SortIncludes: false # Sorting rules for static imports in java # -- Before - static is placed before non-static # -- After - static is placed after non-static # SortJavaStaticImport: Before # # Reorder using statements SortUsingDeclarations: false # # Add spaces after C-style casts SpaceAfterCStyleCast: false # # Add a space after the Template keyword SpaceAfterTemplateKeyword: true # # Add spaces before assignment operators SpaceBeforeAssignmentOperators: true # # Add space before C++11 initializer list # SpaceBeforeCpp11BracedList: true #Add a space before the initialization colon ":" in the constructor # SpaceBeforeCtorInitializerColon: true # Add a space before the inheritance colon ":" in the constructor # SpaceBeforeInheritanceColon: true # Rules for adding spaces before parentheses "()" # -- Never - never add spaces # -- ControlStatements - Add spaces only to control statements (for/if/while...) # -- ControlStatementsExceptForEachMacros - type ControlStatements, just no more spaces after ForEach # -- Always - always add spaces # -- NonEmptyParentheses - similar to Always, but no spaces are added before the blank brackets SpaceBeforeParens: Never #Add a space before the colon ":" in the for loop # SpaceBeforeRangeBasedForLoopColon: true # # Add spaces between empty parentheses "()" SpaceInEmptyParentheses: false # # Number of spaces to add before end-of-line comments (only applies to //) SpacesBeforeTrailingComments: 1 # # Add spaces after the angle brackets "<" and before ">" SpacesInAngles: false # # Add spaces to container (ObjC and JavaScript arrays and dictionaries, etc.) literals SpacesInContainerLiterals: true # # Add spaces between brackets for C-style type conversions SpacesInCStyleCastParentheses: false # # Add spaces after "(" and before ")" in parentheses SpacesInParentheses: false # Add spaces between brackets # When there is no data in the square brackets, it is not affected by this rule (such as blank lambda capture table, variable length array declaration) SpacesInSquareBrackets: false # Language standards: Cpp03, Cpp11, Auto Standard: Auto # #tab width TabWidth: 4 # # Use tab characters: Never, ForIndentation, ForContinuationAndIndentation, Always UseTab: ForIndentation ...
4. Modify configuration file
VSCode configuration files are divided into global configuration files and workspace configuration files. The global configuration file is valid for all workspaces, and the workspace configuration file is valid for the current workspace.
You can modify the global configuration file and the current workspace configuration file at the same time, and the current workspace configuration will overwrite the global configuration.
4.1 Global configuration file modification
In VSCode, press the “F1” button, enter “setting“, and click the option below to open the global settings.json file:
Add the following configuration to the configuration file:
{ // clang-format extended configuration "clang-format.style" : "file", "clang-format.assumeFilename": "/home/user/.clang-format", "clang-format.executable": "/usr/bin/clang-format", "clang-format.fallbackStyle": "Google", "editor.defaultFormatter": "xaver.clang-format" }
Among them, clang-format.assumeFilename is the path of the .clang-format configuration file, and clang-format.executable is the path of the clang-format program.
4.2 Workspace configuration file modification
In VSCode, press the “F1” button, enter “setting“, and click the option below to open the settings.json of the current workspace. document:
Add the following configuration to the configuration file:
{ // clang-format extended configuration "clang-format.style" : "file", "clang-format.assumeFilename": "/home/user/.clang-format", "clang-format.executable": "/usr/bin/clang-format", "clang-format.fallbackStyle": "Google", "editor.defaultFormatter": "xaver.clang-format" }
Among them, clang-format.assumeFilename is the path of the .clang-format configuration file, and clang-format.executable is the path of the clang-format program.
5. Formatting code
- Press Ctrl + Shift + f on the code page.
- Select all codes, right-click,
Format Document With...
, and select Clang-Format.