Project

General

Profile

Actions

Настройка clang-format для Qt

Подключение clang-format

  1. Установить LLVM через установщик
  2. Открыть Qt, Справка -> О Модулях... -> C++, поставить галочку на "Beautifier"
  3. Если хотите, чтобы автоформатирование применялось при сохранении, Инструменты -> Параметры -> Стилизатор -> Основное, поставить галочку "Включить автоформатирование", и в списке выбрать "ClangFormat"
  4. Для форматирования по своему стилю на вкладке Инструменты -> Параметры -> Стилизатор -> Clang Format, выбрать "Использовать особый стиль", затем нажать "Добавить". В поле "Значение" вы можете описать свой стиль.
  5. На вкладке Инструменты -> Параметры -> Стилизатор -> Clang Format в поле Команда Clang Format указать полный путь к утилите clang-format (поставляется в составе LLVM [\\bugmel\distrib\LLVM\], по умолчанию находится по пути C:\Program Files (x86)\LLVM\bin\clang-format.exe)

Пример с настройками нашего codestyle

# Format Style Options - Created with Clang Power Tools
---
AccessModifierOffset: -4
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
BasedOnStyle: Google
BinPackArguments: true
BinPackParameters: true
BraceWrapping: 
  AfterCaseLabel: false
  AfterClass: true
  AfterControlStatement: false
  AfterEnum: false
  AfterFunction: false
  AfterNamespace: false
  AfterObjCDeclaration: false
  AfterStruct: false
  AfterUnion: false
  AfterExternBlock: false
  BeforeCatch: false
  BeforeElse: true
  IndentBraces: false
  SplitEmptyFunction: false
  SplitEmptyRecord: false
  SplitEmptyNamespace: false
  BeforeLambdaBody: false
  BeforeWhile: false
BreakBeforeBraces: Custom
ColumnLimit: 80
IncludeCategories: 
  - Regex: '^<ext/.*\.(h|hpp)'
    Priority: 2
    SortPriority: 0
    CaseSensitive: false
  - Regex: '^<.*\.(h|hpp)>'
    Priority: 1
    SortPriority: 0
    CaseSensitive: false
  - Regex: '^<.*'
    Priority: 2
    SortPriority: 0
    CaseSensitive: false
  - Regex: '.*'
    Priority: 3
    SortPriority: 0
    CaseSensitive: false

IndentWidth: 4
Language: Cpp
ObjCBlockIndentWidth: 4
ObjCSpaceBeforeProtocolList: false
SortIncludes: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: Never
SpaceBeforeRangeBasedForLoopColon: false
TabWidth: 4
UseTab: Never

Также файл можно скачать: attachment:.clang-format

Пример со всеми опциями

# Based on that profile
BasedOnStyle: Google
Language: Cpp
ColumnLimit: 120

BraceWrapping:
   # Class definitions behind
 AfterClass: false
   # Control statements later
 AfterControlStatement:  false
   # Enum defined below
 AfterEnum:  true
   Behind # function definition
 AfterFunction:  false
   # Define the space behind the name
 AfterNamespace: false
   # ObjC defined later
 AfterObjCDeclaration:   false
   # Struct defined below
 AfterStruct:    false
   # Union defined below
 AfterUnion: false
   #ExternBlock defined below
 AfterExternBlock: false
   Before catch #
 BeforeCatch: false
   Before else #
 BeforeElse: false
   # Indent braces
 IndentBraces: false
   # Segmentation empty function
 SplitEmptyFunction: true
   # Segmentation empty record
 SplitEmptyRecord: true
   # Split empty namespace
 SplitEmptyNamespace: true

 # Add space after @property, \ @property (readonly) instead of \ @property (readonly).
ObjCSpaceAfterProperty: true
 # Access specifier (public, private, etc.) offset
AccessModifierOffset: -4
 # The open bracket (open parenthesis, open angle brackets, open bracket) alignment: Align, DontAlign, AlwaysBreak (always open parenthesis after the line feed)
AlignAfterOpenBracket: Align
 # When continuous assignment, align all equal sign
AlignConsecutiveAssignments: false
 # When continuous statement, all statements of alignment variable name
AlignConsecutiveDeclarations: false
 # Left escaped newline (backslash newline) backslash
AlignEscapedNewlinesLeft: true
 # Horizontally aligned operand binary and ternary expressions
AlignOperands: true
 # Align consecutive trailing comments
AlignTrailingComments: true
 # Allow all the parameters declared in the function on the next line
AllowAllParametersOfDeclarationOnNextLine: true
 # Allows a short block on the same line
AllowShortBlocksOnASingleLine: false
 # Allows a short case the label on the same line
AllowShortCaseLabelsOnASingleLine: false
 # Function allows short on the same line: None, InlineOnly (defined in the class), Empty (empty function), Inline (defined in the class, the empty function), All
AllowShortFunctionsOnASingleLine: None
 # Allows a short statement if kept in the same row
AllowShortIfStatementsOnASingleLine: false
 # Allows short cycle remains in the same row
AllowShortLoopsOnASingleLine: false
 # After defining the return type is always wrap (deprecated)
AlwaysBreakAfterDefinitionReturnType:    None
 # Line after the return type is always changing: None, All, TopLevel (top-level function, the function is not included in the class),
 # AllDefinitions (all definitions, not including the declaration), TopLevelDefinitions (defined all the top functions)
AlwaysBreakAfterReturnType:  None
 # Always before multi-line string literal newline
AlwaysBreakBeforeMultilineStrings: false
 # Always wrap in a statement after the template
AlwaysBreakTemplateDeclarations: false
 # False representation function arguments are either on the same line, or have each row
BinPackArguments: true
 # False indicates that all formal parameters are either on the same line, or have each row
BinPackParameters: true
 # Braces wrap only when BreakBeforeBraces set to Custom effective
 # Wrap before binary operators: None (after a newline operator), NonAssignment (non-wrap before the assignment operator), All (operator before newline)
BreakBeforeBinaryOperators: NonAssignment
 # Braces line before change: Attach (the braces are always attached to the surrounding context), the Linux (in addition to the function, and namespace class definition, and the like Attach),
 # Mozilla (except the enumeration, the function, definition of recording, and the like Attach), Stroustrup (in addition to the function definition, catch, else, and is similar to Attach),
 # Allman (always before braces wrap), GNU (always before braces wrap and indent for additional braces control statements), WebKit (before the function wrap), Custom
 # Note: This statement is considered to belong to function block
BreakBeforeBraces: Custom
 # Ternary operator before linefeed
BreakBeforeTernaryOperators: true
 # Comma before the constructor initialization list of wrap
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: true
 Comment # Description of special significance regular expression, it should not be split into multiple lines or otherwise change
CommentPragmas: '^ IWYU pragma:'
 # Constructor initializer list are either on the same line, or have each row
ConstructorInitializerAllOnOneLineOrOnePerLine: true
 # Constructor comfort of a list of all line breaks
AllowAllConstructorInitializersOnNextLine: false
 Indent width initialization list of the constructor #
ConstructorInitializerIndentWidth: 4
 Indent a continuation of the line width #
ContinuationIndentWidth: 4
 # C ++ removal list initialization 11 and braces {} after the front space
Cpp11BracedListStyle: true
 # The most common inherited pointers and references alignment
DerivePointerAlignment: false
 # Closed format
DisableFormat:  false
 # Calls and automatic detection function define the format for each row whether a parameter (Experimental)
ExperimentalAutoDetectBinPacking:    false
 # Amended namespace Annotations
FixNamespaceComments: true
 # Needs to be interpreted as foreach loop instead of a macro function calls
ForEachMacros:
 - foreach
 - Q_FOREACH
 - BOOST_FOREACH
 #include #include # sort of match the regular expression has a corresponding priority, then not match the default priority is INT_MAX (the smaller the priority ordering more front),
 # You can define negative priorities in order to ensure that certain #include always on top
IncludeCategories:
 - Regex:           '^<ext/.*\.h>'
   Priority:        2
 - Regex:           '^<.*\.h>'
   Priority:        1
 - Regex:           '^<.*'
   Priority:        2
 - Regex:           '.*'
   Priority:        3

IncludeIsMainRegex: '([-_](test|unittest))?$'
 # Indent label case
IndentCaseLabels: true
 # Indentation width
IndentWidth:    4
 # Function return type change lines, indentation function name function declaration or function definition
IndentWrappedFunctionNames:    false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
 # Retain the blank line at the beginning of the block
KeepEmptyLinesAtTheStartOfBlocks:    true
 # Macro being the beginning of a block of expression
MacroBlockBegin:    ''
 # End of a macro block of a regular expression
MacroBlockEnd:    ''
 The maximum number of consecutive blank lines #
MaxEmptyLinesToKeep: 1
 # Namespace indent: (Content indent nested namespace) None, Inner, All
NamespaceIndentation:    None
 Indent width used ObjC block #
ObjCBlockIndentWidth:    4
 # Add a space before the protocol list of ObjC
ObjCSpaceBeforeProtocolList: false
 # In the call (after calling the penalty wrap the function
PenaltyBreakBeforeFirstCallParameter:    19
 # Introduction of penalty wrap in a comment
PenaltyBreakComment:    300
 penalty # for the first time before << wrap
PenaltyBreakFirstLessLess:    120
 # Wrap penalty introduced in a string literals
PenaltyBreakString:    1000
# For each line outside the limit on the number of characters in the character of penalty
PenaltyExcessCharacter:    1000000
 # The function returns the type of penalty into its own row
PenaltyReturnTypeOnItsOwnLine:    60
 # Pointers and references alignment: 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
 # Allowed to re-format comments
ReflowComments:    true
 # Allow sorting #include
SortIncludes:    true
SortUsingDeclarations: true
 # Add a space after the C-style casts
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 the opening parenthesis: Never, ControlStatements, Always
SpaceBeforeParens:    ControlStatements
 # Add a space empty parentheses
SpaceInEmptyParentheses:    false
 # Before the number of spaces trailing comments added (only applicable to //)
SpacesBeforeTrailingComments:    2
 # In angle brackets <and after> before adding spaces
SpacesInAngles:    false
 # Add a space literal container (ObjC and JavaScript arrays and dictionaries, etc.)
SpacesInContainerLiterals:    true
 # Add a space in C-style casts in parentheses
SpacesInCStyleCastParentheses: false
 # Add a space in parentheses (and after) ago
SpacesInParentheses: false
 # Declaration in square brackets [and after] before adding a space, lamda expressions, and does not indicate the size of the array is not affected
SpacesInSquareBrackets:    false
 # Standard: Cpp03, Cpp11, Auto
Standard:    Cpp11
 # Tab width
TabWidth:    4
 # Use the tab characters: Never, ForIndentation, ForContinuationAndIndentation, Always
UseTab:    Never

Updated by Redmine Admin over 1 year ago · 1 revisions