Use the Visual Studio Code editor to format code with Clang-Format
Article directory
- Format code with Clang-Format using the Visual Studio Code editor
- Preface
- 1. Install the plug-in
- 2. Configure the plug-in environment
-
- 1. Find the plugin path
- 2. Set up the plug-in environment
- 3. Fill in the plug-in tool path
- 4. Format document generation/production
- 5. Fill in the format document path
- 6. Format test
- 7.Format document
- 3. Notes on configuration files
- Summarize
Foreword
For vscode, it is lightweight and can install various plug-ins. But for formatting code, using the Clang-Format plug-in is the most convenient and lightweight tool I can find currently.
1. Install plug-in
1. Search for the plug-in Clang-Format in the extension and install version v1.9.0
2. Configure plug-in environment
1. Find the plug-in path
Find the installation path of the plug-in, for example, my path is C:\Users\ASUS.vscode\extensions\ms-vscode.cpptools-1.17.5-win32-x64\LLVM\bin
2. Set up the plug-in environment
Copy this path, then search for format in the settings of vscode and select Clang-format configuration
3. Fill in the plug-in tool path
Fill in the plugin path just found in the clang-format.executable column, such as C:\Users\ASUS.vscode\extensions\ms-vscode.cpptools-1.17.5-win32-x64\LLVM\bin strong>
4. Format document generation/production
For this plug-in, it actually relies on LLVM for formatting. Generally speaking, it needs to be generated using LLVM software. However, for the convenience of readers, I will not show how to generate it here. I will put the format document here directly, and It is also what I am using. It has been optimized and is more comprehensive than the automatically generated format. Because the content is too long, I put it at the end of the article. Change the file name to .clang-format and put it in the directory you want to put it in. Mine is as shown below:
Tips: There are also .clang-format format documents in my resources, you can download them
5. Fill in the format document path
Based on the third point above, find and fill in the path to the format document. Note the prefix file:C:\Users\ASUS.vscode\extensions\ms-vscode.cpptools-1.17.5-win32-x64\ LLVM\bin\ .clang-format
6. Formatting test
1. Formatting method: Enter the editing file, right-click and select Format Document. If the current editor has multiple formatting plug-ins, you can click <
2. If you only want to format a part, you can select that part, right-click and select Format Selection.
3. There is a choice in the format document, the default is C++
# Language: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto Language: Cpp
2. After formatting, this is the effect:
7. Format document
After saving, you need to change the file name to: .clang-format
Tips: There is a .
in front of the file name.
--- # Language: None, Cpp, Java, JavaScript, ObjC, Proto, TableGen, TextProto Language: Cpp BasedOnStyle: WebKit # Offset of access specifiers (public, private, etc.) AccessModifierOffset: -4 # Alignment after opening brackets (opening round brackets, opening angle brackets, opening square brackets): Align, DontAlign, AlwaysBreak (always break after opening brackets) AlignAfterOpenBracket: Align # Align array columns AlignArrayOfStructures: None # When assigning values continuously, align all equal signs AlignConsecutiveAssignments: None # Align contiguous bit fields AlignConsecutiveBitFields: None # When declaring consecutively, align all declared variable names AlignConsecutiveDeclarations: None # Align continuous macro definitions AlignConsecutiveMacros: AcrossComments # Escape backslashes for newlines (use backslashes for newlines) AlignEscapedNewlines: Left # Operand alignment AlignOperands: Align # Trailing comment alignment AlignTrailingComments: true # Allow function parameters to be on one line AllowAllArgumentsOnNextLine: true # Allow all parameters of a function declaration to be placed on one line AllowAllParametersOfDeclarationOnNextLine: true # Allow short blocks to be placed on the same line AllowShortBlocksOnASingleLine: Never # Allow short case tags to be placed on the same line AllowShortCaseLabelsOnASingleLine: false # Allow short enumerations to be placed on the same line AllowShortEnumsOnASingleLine: false # Allow short functions to be placed on the same line AllowShortFunctionsOnASingleLine: Empty # Allow short if statements to stay on the same line AllowShortIfStatementsOnASingleLine: Never # Allow short anonymous function lambda expressions to be placed on the same line AllowShortLambdasOnASingleLine: Empty # Allow short while loops to stay on the same line AllowShortLoopsOnASingleLine: false #Always wrap after return type AlwaysBreakAfterReturnType: None #Always wrap before multi-line string literals AlwaysBreakBeforeMultilineStrings: false #Always wrap after template declaration AlwaysBreakTemplateDeclarations: MultiLine # Macro attributes AttributeMacros: ['__capability', '__output', '__ununsed'] # Indicates 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: true # Bitfield colon alignment BitFieldColonSpacing : Both # Braces are broken. This is only valid when BreakBeforeBraces is set to Custom. If other configurations are set, the following will not take effect. BraceWrapping: AfterCaseLabel: true AfterClass: false AfterControlStatement: Never AfterEnum: false AfterFunction: true AfterNamespace: true AfterObjCDeclaration: false AfterStruct: false AfterUnion: false AfterExternBlock: false BeforeCatch: false BeforeElse: false BeforeLambdaBody: false BeforeWhile: false IndentBraces: false SplitEmptyFunction: true SplitEmptyRecord: true SplitEmptyNamespace: true # Wrap a new line after the comment in the java field BreakAfterJavaFieldAnnotations: false # wrap before binary operator BreakBeforeBinaryOperators: None # Wrap before the braces. If it is not Custom, the above BraceWrapping will not take effect. BreakBeforeBraces: Allman #Newline before concept # BreakBeforeConceptDeclarations: Never # wrap before ternary operator BreakBeforeTernaryOperators: true #Constructor initializer wrapping style BreakConstructorInitializers: BeforeColon #Inherit list style BreakInheritanceList: AfterColon # String wrapping style BreakStringLiterals: false #Limit of characters per line, 0 means no limit ColumnLimit: 150 # Regular expression describing a comment with special meaning that should not be split into multiple lines or otherwise altered CommentPragmas: '^ IWYU pragma:' # Declare each namespace on a new line CompactNamespaces: false #Indentation width of initialization list of constructor ConstructorInitializerIndentWidth: 4 # Indent width of continued lines ContinuationIndentWidth: 4 # Remove the spaces after the braces {<!-- --> and before } in C++11 list initialization Cpp11BracedListStyle: true # Inherit the most commonly used line breaking methods DeriveLineEnding: true # Inherit the most commonly used alignment methods of pointers and references DerivePointerAlignment: false # Turn off formatting DisableFormat: false # Remove all empty lines after access modifiers EmptyLineAfterAccessModifier: Never # Only add empty lines if the access modifier starts a new logical block EmptyLineBeforeAccessModifier: Never # Automatically detect whether function calls and definitions are formatted as one parameter per line (Experimental) ExperimentalAutoDetectBinPacking: false # Automatically add namespace comments FixNamespaceComments: false # Macros that need to be interpreted as foreach loops rather than function calls ForEachMacros: ['RANGES_FOR', 'FOREACH'] IfMacros: ['IF'] # Multiple #include blocks are merged together and sorted into one IncludeBlocks: Merge #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 SortPriority: 0 CaseSensitive: false - Regex: '^(<|"(gtest|gmock|isl|json)/)' Priority: 3 SortPriority: 0 CaseSensitive: false - Regex: '.*' Priority: 1 SortPriority: 0 CaseSensitive: false IncludeIsMainRegex: '(Test)?$' IncludeIsMainSourceRegex: '' # Indent access modifier IndentAccessModifiers: false # Indent case tags IndentCaseLabels: false # The block following the case label uses the same indentation level as the case label IndentCaseBlocks: false # Backward compatibility with indenting external blocks IndentExternBlock: AfterExternBlock # Indent goto tags. IndentGotoLabels: false # Indent preprocessor directives IndentPPDirectives: BeforeHash # Indent the requires clause in the template IndentRequires: false #Indent width IndentWidth: 4 # When the function return type is wrapped, indent the function declaration or function name of the function definition. IndentWrappedFunctionNames: false #InsertBraces: true # Insert trailing comma InsertTrailingCommas: None # Preserve JavaScript string quotes JavaScriptQuotes: Leave # Wrap JavaScript import/export statements JavaScriptWrapImports: true # Keep the empty line at the beginning of the block KeepEmptyLinesAtTheStartOfBlocks: false # Align lambda body relative to lambda signature LambdaBodyIndentation: Signature # 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 NamespaceIndentation: All ObjCBinPackProtocolList: Auto # Indent width when using ObjC blocks ObjCBlockIndentWidth: 4 ObjCBreakBeforeNestedBlockParam: true # Add a space after ObjC's @property ObjCSpaceAfterProperty: false # Add a space before the ObjC protocol list ObjCSpaceBeforeProtocolList: true # Number of columns to indent preprocessor statements PPIndentWidth: -1 PenaltyBreakAssignment: 2 PenaltyBreakBeforeFirstCallParameter: 19 PenaltyBreakComment: 300 PenaltyBreakFirstLessLess: 120 PenaltyBreakString: 1000 PenaltyBreakTemplateDeclaration: 10 PenaltyExcessCharacter: 1000000 PenaltyReturnTypeOnItsOwnLine: 60 PenaltyIndentedWhitespace: 0 # Pointer alignment: Left, Right, Middle PointerAlignment: Right # Alignment of references ReferenceAlignment: Pointer # Allow comments to be re-formatted ReflowComments: true #RemoveBracesLLVM: false # The maximum number of expanded lines spanned by a short namespace ShortNamespaceLines: 1 # Allow sorting #include SortIncludes: CaseSensitive # java static import is placed before non-static import SortJavaStaticImport: Before # Sort using declarations SortUsingDeclarations: true # Add spaces after C-style casts SpaceAfterCStyleCast: false # Add space after ! SpaceAfterLogicalNot: false # Add a space after the Template keyword SpaceAfterTemplateKeyword: true # Don't make sure there are spaces around the pointer qualifier SpaceAroundPointerQualifiers: Default # Add spaces before assignment operators SpaceBeforeAssignmentOperators: true # Do not add spaces before case colon SpaceBeforeCaseColon: false # Don't add spaces before C++11 brace lists SpaceBeforeCpp11BracedList: false # Add space before constructor initializer colon SpaceBeforeCtorInitializerColon: true #Add space before inheritance colon SpaceBeforeInheritanceColon: true # Add a space before the opening parenthesis SpaceBeforeParens: ControlStatements # Add space before colon in range based for loop SpaceBeforeRangeBasedForLoopColon: true # Space before square brackets SpaceBeforeSquareBrackets: false # {<!-- -->}space in between SpaceInEmptyBlock: false # Add spaces between empty parentheses SpaceInEmptyParentheses: false # Number of spaces to add before trailing comments (only applies to //) SpacesBeforeTrailingComments: 3 # Add spaces after < and before > in angle brackets SpacesInAngles: Never # Add spaces between brackets for C-style type conversions SpacesInCStyleCastParentheses: false # Do not insert spaces around if/for/switch/while conditions SpacesInConditionalStatement: false # Add spaces to container (ObjC and JavaScript arrays and dictionaries, etc.) literals SpacesInContainerLiterals: true # How many spaces are allowed at the beginning of a line comment. To disable the maximum value, set it to -1, otherwise the maximum value takes precedence over the minimum value SpacesInLineCommentPrefix: Minimum: 1 Maximum: -1 # 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 Standard: Auto # Macro definitions preceding statements are ignored as if they were an attribute StatementAttributeLikeMacros: -Q_EMIT # Macro definitions that should be interpreted as complete statements StatementMacros: - Q_UNUSED - QT_REQUIRE_VERSION #tab width TabWidth: 4 # Use \r\ newline instead of \ UseCRLF: false # Use tab characters: ForIndentation - only use tab characters for indentation UseTab: Never # Space-sensitive macro definition WhitespaceSensitiveMacros: - STRINGIZE -PP_STRINGIZE - BOOST_PP_STRINGIZE - NS_SWIFT_NAME - CF_SWIFT_NAME ...
3. Notes on configuration files
1. In this article, you can see that the plug-in environment I configured in Workspace will not take effect in other workspaces. If you want to use it in all projects, configure it in the User Area.
2. For the Clang-format plug-in, vscode will secretly update itself, so when the plug-in updates something, the path of the file will change, causing the formatting to fail;
3. Solution to plug-in updates: You can copy a copy of the plug-in yourself, and then change the path to the copied file path. For example, this is my file and path:
3.1. Here I copied a plug-in package and added the suffix << - static>>
3.2. Then modify clang-format.executable and clang-format.style in the user area.
Summary
no summary