1========================== 2Clang-Format Style Options 3========================== 4 5:doc:`ClangFormatStyleOptions` describes configurable formatting style options 6supported by :doc:`LibFormat` and :doc:`ClangFormat`. 7 8When using :program:`clang-format` command line utility or 9``clang::format::reformat(...)`` functions from code, one can either use one of 10the predefined styles (LLVM, Google, Chromium, Mozilla, WebKit) or create a 11custom style by configuring specific style options. 12 13 14Configuring Style with clang-format 15=================================== 16 17:program:`clang-format` supports two ways to provide custom style options: 18directly specify style configuration in the ``-style=`` command line option or 19use ``-style=file`` and put style configuration in the ``.clang-format`` or 20``_clang-format`` file in the project directory. 21 22When using ``-style=file``, :program:`clang-format` for each input file will 23try to find the ``.clang-format`` file located in the closest parent directory 24of the input file. When the standard input is used, the search is started from 25the current directory. 26 27The ``.clang-format`` file uses YAML format: 28 29.. code-block:: yaml 30 31 key1: value1 32 key2: value2 33 # A comment. 34 ... 35 36The configuration file can consist of several sections each having different 37``Language:`` parameter denoting the programming language this section of the 38configuration is targeted at. See the description of the **Language** option 39below for the list of supported languages. The first section may have no 40language set, it will set the default style options for all lanugages. 41Configuration sections for specific language will override options set in the 42default section. 43 44When :program:`clang-format` formats a file, it auto-detects the language using 45the file name. When formatting standard input or a file that doesn't have the 46extension corresponding to its language, ``-assume-filename=`` option can be 47used to override the file name :program:`clang-format` uses to detect the 48language. 49 50An example of a configuration file for multiple languages: 51 52.. code-block:: yaml 53 54 --- 55 # We'll use defaults from the LLVM style, but with 4 columns indentation. 56 BasedOnStyle: LLVM 57 IndentWidth: 4 58 --- 59 Language: Cpp 60 # Force pointers to the type for C++. 61 DerivePointerAlignment: false 62 PointerAlignment: Left 63 --- 64 Language: JavaScript 65 # Use 100 columns for JS. 66 ColumnLimit: 100 67 --- 68 Language: Proto 69 # Don't format .proto files. 70 DisableFormat: true 71 ... 72 73An easy way to get a valid ``.clang-format`` file containing all configuration 74options of a certain predefined style is: 75 76.. code-block:: console 77 78 clang-format -style=llvm -dump-config > .clang-format 79 80When specifying configuration in the ``-style=`` option, the same configuration 81is applied for all input files. The format of the configuration is: 82 83.. code-block:: console 84 85 -style='{key1: value1, key2: value2, ...}' 86 87 88Disabling Formatting on a Piece of Code 89======================================= 90 91Clang-format understands also special comments that switch formatting in a 92delimited range. The code between a comment ``// clang-format off`` or 93``/* clang-format off */`` up to a comment ``// clang-format on`` or 94``/* clang-format on */`` will not be formatted. The comments themselves 95will be formatted (aligned) normally. 96 97.. code-block:: c++ 98 99 int formatted_code; 100 // clang-format off 101 void unformatted_code ; 102 // clang-format on 103 void formatted_code_again; 104 105 106Configuring Style in Code 107========================= 108 109When using ``clang::format::reformat(...)`` functions, the format is specified 110by supplying the `clang::format::FormatStyle 111<http://clang.llvm.org/doxygen/structclang_1_1format_1_1FormatStyle.html>`_ 112structure. 113 114 115Configurable Format Style Options 116================================= 117 118This section lists the supported style options. Value type is specified for 119each option. For enumeration types possible values are specified both as a C++ 120enumeration member (with a prefix, e.g. ``LS_Auto``), and as a value usable in 121the configuration (without a prefix: ``Auto``). 122 123 124**BasedOnStyle** (``string``) 125 The style used for all options not specifically set in the configuration. 126 127 This option is supported only in the :program:`clang-format` configuration 128 (both within ``-style='{...}'`` and the ``.clang-format`` file). 129 130 Possible values: 131 132 * ``LLVM`` 133 A style complying with the `LLVM coding standards 134 <http://llvm.org/docs/CodingStandards.html>`_ 135 * ``Google`` 136 A style complying with `Google's C++ style guide 137 <http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml>`_ 138 * ``Chromium`` 139 A style complying with `Chromium's style guide 140 <http://www.chromium.org/developers/coding-style>`_ 141 * ``Mozilla`` 142 A style complying with `Mozilla's style guide 143 <https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style>`_ 144 * ``WebKit`` 145 A style complying with `WebKit's style guide 146 <http://www.webkit.org/coding/coding-style.html>`_ 147 148.. START_FORMAT_STYLE_OPTIONS 149 150**AccessModifierOffset** (``int``) 151 The extra indent or outdent of access modifiers, e.g. ``public:``. 152 153**AlignAfterOpenBracket** (``bool``) 154 If ``true``, horizontally aligns arguments after an open bracket. 155 156 This applies to round brackets (parentheses), angle brackets and square 157 brackets. This will result in formattings like 158 \code 159 someLongFunction(argument1, 160 argument2); 161 \endcode 162 163**AlignConsecutiveAssignments** (``bool``) 164 If ``true``, aligns consecutive assignments. 165 166 This will align the assignment operators of consecutive lines. This 167 will result in formattings like 168 \code 169 int aaaa = 12; 170 int b = 23; 171 int ccc = 23; 172 \endcode 173 174**AlignEscapedNewlinesLeft** (``bool``) 175 If ``true``, aligns escaped newlines as far left as possible. 176 Otherwise puts them into the right-most column. 177 178**AlignOperands** (``bool``) 179 If ``true``, horizontally align operands of binary and ternary 180 expressions. 181 182**AlignTrailingComments** (``bool``) 183 If ``true``, aligns trailing comments. 184 185**AllowAllParametersOfDeclarationOnNextLine** (``bool``) 186 Allow putting all parameters of a function declaration onto 187 the next line even if ``BinPackParameters`` is ``false``. 188 189**AllowShortBlocksOnASingleLine** (``bool``) 190 Allows contracting simple braced statements to a single line. 191 192 E.g., this allows ``if (a) { return; }`` to be put on a single line. 193 194**AllowShortCaseLabelsOnASingleLine** (``bool``) 195 If ``true``, short case labels will be contracted to a single line. 196 197**AllowShortFunctionsOnASingleLine** (``ShortFunctionStyle``) 198 Dependent on the value, ``int f() { return 0; }`` can be put 199 on a single line. 200 201 Possible values: 202 203 * ``SFS_None`` (in configuration: ``None``) 204 Never merge functions into a single line. 205 * ``SFS_Empty`` (in configuration: ``Empty``) 206 Only merge empty functions. 207 * ``SFS_Inline`` (in configuration: ``Inline``) 208 Only merge functions defined inside a class. Implies "empty". 209 * ``SFS_All`` (in configuration: ``All``) 210 Merge all functions fitting on a single line. 211 212 213**AllowShortIfStatementsOnASingleLine** (``bool``) 214 If ``true``, ``if (a) return;`` can be put on a single 215 line. 216 217**AllowShortLoopsOnASingleLine** (``bool``) 218 If ``true``, ``while (true) continue;`` can be put on a 219 single line. 220 221**AlwaysBreakAfterDefinitionReturnType** (``DefinitionReturnTypeBreakingStyle``) 222 The function definition return type breaking style to use. 223 224 Possible values: 225 226 * ``DRTBS_None`` (in configuration: ``None``) 227 Break after return type automatically. 228 ``PenaltyReturnTypeOnItsOwnLine`` is taken into account. 229 * ``DRTBS_All`` (in configuration: ``All``) 230 Always break after the return type. 231 * ``DRTBS_TopLevel`` (in configuration: ``TopLevel``) 232 Always break after the return types of top level functions. 233 234 235**AlwaysBreakBeforeMultilineStrings** (``bool``) 236 If ``true``, always break before multiline string literals. 237 238 This flag is mean to make cases where there are multiple multiline strings 239 in a file look more consistent. Thus, it will only take effect if wrapping 240 the string at that point leads to it being indented 241 ``ContinuationIndentWidth`` spaces from the start of the line. 242 243**AlwaysBreakTemplateDeclarations** (``bool``) 244 If ``true``, always break after the ``template<...>`` of a 245 template declaration. 246 247**BinPackArguments** (``bool``) 248 If ``false``, a function call's arguments will either be all on the 249 same line or will have one line each. 250 251**BinPackParameters** (``bool``) 252 If ``false``, a function declaration's or function definition's 253 parameters will either all be on the same line or will have one line each. 254 255**BreakBeforeBinaryOperators** (``BinaryOperatorStyle``) 256 The way to wrap binary operators. 257 258 Possible values: 259 260 * ``BOS_None`` (in configuration: ``None``) 261 Break after operators. 262 * ``BOS_NonAssignment`` (in configuration: ``NonAssignment``) 263 Break before operators that aren't assignments. 264 * ``BOS_All`` (in configuration: ``All``) 265 Break before operators. 266 267 268**BreakBeforeBraces** (``BraceBreakingStyle``) 269 The brace breaking style to use. 270 271 Possible values: 272 273 * ``BS_Attach`` (in configuration: ``Attach``) 274 Always attach braces to surrounding context. 275 * ``BS_Linux`` (in configuration: ``Linux``) 276 Like ``Attach``, but break before braces on function, namespace and 277 class definitions. 278 * ``BS_Mozilla`` (in configuration: ``Mozilla``) 279 Like ``Attach``, but break before braces on enum, function, and record 280 definitions. 281 * ``BS_Stroustrup`` (in configuration: ``Stroustrup``) 282 Like ``Attach``, but break before function definitions, 'catch', and 'else'. 283 * ``BS_Allman`` (in configuration: ``Allman``) 284 Always break before braces. 285 * ``BS_GNU`` (in configuration: ``GNU``) 286 Always break before braces and add an extra level of indentation to 287 braces of control statements, not to those of class, function 288 or other definitions. 289 * ``BS_WebKit`` (in configuration: ``WebKit``) 290 Like ``Attach``, but break before functions. 291 292 293**BreakBeforeTernaryOperators** (``bool``) 294 If ``true``, ternary operators will be placed after line breaks. 295 296**BreakConstructorInitializersBeforeComma** (``bool``) 297 Always break constructor initializers before commas and align 298 the commas with the colon. 299 300**ColumnLimit** (``unsigned``) 301 The column limit. 302 303 A column limit of ``0`` means that there is no column limit. In this case, 304 clang-format will respect the input's line breaking decisions within 305 statements unless they contradict other rules. 306 307**CommentPragmas** (``std::string``) 308 A regular expression that describes comments with special meaning, 309 which should not be split into lines or otherwise changed. 310 311**ConstructorInitializerAllOnOneLineOrOnePerLine** (``bool``) 312 If the constructor initializers don't fit on a line, put each 313 initializer on its own line. 314 315**ConstructorInitializerIndentWidth** (``unsigned``) 316 The number of characters to use for indentation of constructor 317 initializer lists. 318 319**ContinuationIndentWidth** (``unsigned``) 320 Indent width for line continuations. 321 322**Cpp11BracedListStyle** (``bool``) 323 If ``true``, format braced lists as best suited for C++11 braced 324 lists. 325 326 Important differences: 327 - No spaces inside the braced list. 328 - No line break before the closing brace. 329 - Indentation with the continuation indent, not with the block indent. 330 331 Fundamentally, C++11 braced lists are formatted exactly like function 332 calls would be formatted in their place. If the braced list follows a name 333 (e.g. a type or variable name), clang-format formats as if the ``{}`` were 334 the parentheses of a function call with that name. If there is no name, 335 a zero-length name is assumed. 336 337**DerivePointerAlignment** (``bool``) 338 If ``true``, analyze the formatted file for the most common 339 alignment of & and \*. ``PointerAlignment`` is then used only as fallback. 340 341**DisableFormat** (``bool``) 342 Disables formatting completely. 343 344**ExperimentalAutoDetectBinPacking** (``bool``) 345 If ``true``, clang-format detects whether function calls and 346 definitions are formatted with one parameter per line. 347 348 Each call can be bin-packed, one-per-line or inconclusive. If it is 349 inconclusive, e.g. completely on one line, but a decision needs to be 350 made, clang-format analyzes whether there are other bin-packed cases in 351 the input file and act accordingly. 352 353 NOTE: This is an experimental flag, that might go away or be renamed. Do 354 not use this in config files, etc. Use at your own risk. 355 356**ForEachMacros** (``std::vector<std::string>``) 357 A vector of macros that should be interpreted as foreach loops 358 instead of as function calls. 359 360 These are expected to be macros of the form: 361 \code 362 FOREACH(<variable-declaration>, ...) 363 <loop-body> 364 \endcode 365 366 For example: BOOST_FOREACH. 367 368**IndentCaseLabels** (``bool``) 369 Indent case labels one level from the switch statement. 370 371 When ``false``, use the same indentation level as for the switch statement. 372 Switch statement body is always indented one level more than case labels. 373 374**IndentWidth** (``unsigned``) 375 The number of columns to use for indentation. 376 377**IndentWrappedFunctionNames** (``bool``) 378 Indent if a function definition or declaration is wrapped after the 379 type. 380 381**KeepEmptyLinesAtTheStartOfBlocks** (``bool``) 382 If true, empty lines at the start of blocks are kept. 383 384**Language** (``LanguageKind``) 385 Language, this format style is targeted at. 386 387 Possible values: 388 389 * ``LK_None`` (in configuration: ``None``) 390 Do not use. 391 * ``LK_Cpp`` (in configuration: ``Cpp``) 392 Should be used for C, C++, ObjectiveC, ObjectiveC++. 393 * ``LK_Java`` (in configuration: ``Java``) 394 Should be used for Java. 395 * ``LK_JavaScript`` (in configuration: ``JavaScript``) 396 Should be used for JavaScript. 397 * ``LK_Proto`` (in configuration: ``Proto``) 398 Should be used for Protocol Buffers 399 (https://developers.google.com/protocol-buffers/). 400 401 402**MacroBlockBegin** (``std::string``) 403 A regular expression matching macros that start a block. 404 405**MacroBlockEnd** (``std::string``) 406 A regular expression matching macros that end a block. 407 408**MaxEmptyLinesToKeep** (``unsigned``) 409 The maximum number of consecutive empty lines to keep. 410 411**NamespaceIndentation** (``NamespaceIndentationKind``) 412 The indentation used for namespaces. 413 414 Possible values: 415 416 * ``NI_None`` (in configuration: ``None``) 417 Don't indent in namespaces. 418 * ``NI_Inner`` (in configuration: ``Inner``) 419 Indent only in inner namespaces (nested in other namespaces). 420 * ``NI_All`` (in configuration: ``All``) 421 Indent in all namespaces. 422 423 424**ObjCBlockIndentWidth** (``unsigned``) 425 The number of characters to use for indentation of ObjC blocks. 426 427**ObjCSpaceAfterProperty** (``bool``) 428 Add a space after ``@property`` in Objective-C, i.e. use 429 ``\@property (readonly)`` instead of ``\@property(readonly)``. 430 431**ObjCSpaceBeforeProtocolList** (``bool``) 432 Add a space in front of an Objective-C protocol list, i.e. use 433 ``Foo <Protocol>`` instead of ``Foo<Protocol>``. 434 435**PenaltyBreakBeforeFirstCallParameter** (``unsigned``) 436 The penalty for breaking a function call after "call(". 437 438**PenaltyBreakComment** (``unsigned``) 439 The penalty for each line break introduced inside a comment. 440 441**PenaltyBreakFirstLessLess** (``unsigned``) 442 The penalty for breaking before the first ``<<``. 443 444**PenaltyBreakString** (``unsigned``) 445 The penalty for each line break introduced inside a string literal. 446 447**PenaltyExcessCharacter** (``unsigned``) 448 The penalty for each character outside of the column limit. 449 450**PenaltyReturnTypeOnItsOwnLine** (``unsigned``) 451 Penalty for putting the return type of a function onto its own 452 line. 453 454**PointerAlignment** (``PointerAlignmentStyle``) 455 Pointer and reference alignment style. 456 457 Possible values: 458 459 * ``PAS_Left`` (in configuration: ``Left``) 460 Align pointer to the left. 461 * ``PAS_Right`` (in configuration: ``Right``) 462 Align pointer to the right. 463 * ``PAS_Middle`` (in configuration: ``Middle``) 464 Align pointer in the middle. 465 466 467**SpaceAfterCStyleCast** (``bool``) 468 If ``true``, a space may be inserted after C style casts. 469 470**SpaceBeforeAssignmentOperators** (``bool``) 471 If ``false``, spaces will be removed before assignment operators. 472 473**SpaceBeforeParens** (``SpaceBeforeParensOptions``) 474 Defines in which cases to put a space before opening parentheses. 475 476 Possible values: 477 478 * ``SBPO_Never`` (in configuration: ``Never``) 479 Never put a space before opening parentheses. 480 * ``SBPO_ControlStatements`` (in configuration: ``ControlStatements``) 481 Put a space before opening parentheses only after control statement 482 keywords (``for/if/while...``). 483 * ``SBPO_Always`` (in configuration: ``Always``) 484 Always put a space before opening parentheses, except when it's 485 prohibited by the syntax rules (in function-like macro definitions) or 486 when determined by other style rules (after unary operators, opening 487 parentheses, etc.) 488 489 490**SpaceInEmptyParentheses** (``bool``) 491 If ``true``, spaces may be inserted into '()'. 492 493**SpacesBeforeTrailingComments** (``unsigned``) 494 The number of spaces before trailing line comments 495 (``//`` - comments). 496 497 This does not affect trailing block comments (``/**/`` - comments) as those 498 commonly have different usage patterns and a number of special cases. 499 500**SpacesInAngles** (``bool``) 501 If ``true``, spaces will be inserted after '<' and before '>' in 502 template argument lists 503 504**SpacesInCStyleCastParentheses** (``bool``) 505 If ``true``, spaces may be inserted into C style casts. 506 507**SpacesInContainerLiterals** (``bool``) 508 If ``true``, spaces are inserted inside container literals (e.g. 509 ObjC and Javascript array and dict literals). 510 511**SpacesInParentheses** (``bool``) 512 If ``true``, spaces will be inserted after '(' and before ')'. 513 514**SpacesInSquareBrackets** (``bool``) 515 If ``true``, spaces will be inserted after '[' and before ']'. 516 517**Standard** (``LanguageStandard``) 518 Format compatible with this standard, e.g. use 519 ``A<A<int> >`` instead of ``A<A<int>>`` for LS_Cpp03. 520 521 Possible values: 522 523 * ``LS_Cpp03`` (in configuration: ``Cpp03``) 524 Use C++03-compatible syntax. 525 * ``LS_Cpp11`` (in configuration: ``Cpp11``) 526 Use features of C++11 (e.g. ``A<A<int>>`` instead of 527 ``A<A<int> >``). 528 * ``LS_Auto`` (in configuration: ``Auto``) 529 Automatic detection based on the input. 530 531 532**TabWidth** (``unsigned``) 533 The number of columns used for tab stops. 534 535**UseTab** (``UseTabStyle``) 536 The way to use tab characters in the resulting file. 537 538 Possible values: 539 540 * ``UT_Never`` (in configuration: ``Never``) 541 Never use tab. 542 * ``UT_ForIndentation`` (in configuration: ``ForIndentation``) 543 Use tabs only for indentation. 544 * ``UT_Always`` (in configuration: ``Always``) 545 Use tabs whenever we need to fill whitespace that spans at least from 546 one tab stop to the next one. 547 548 549.. END_FORMAT_STYLE_OPTIONS 550 551Examples 552======== 553 554A style similar to the `Linux Kernel style 555<https://www.kernel.org/doc/Documentation/CodingStyle>`_: 556 557.. code-block:: yaml 558 559 BasedOnStyle: LLVM 560 IndentWidth: 8 561 UseTab: Always 562 BreakBeforeBraces: Linux 563 AllowShortIfStatementsOnASingleLine: false 564 IndentCaseLabels: false 565 566The result is (imagine that tabs are used for indentation here): 567 568.. code-block:: c++ 569 570 void test() 571 { 572 switch (x) { 573 case 0: 574 case 1: 575 do_something(); 576 break; 577 case 2: 578 do_something_else(); 579 break; 580 default: 581 break; 582 } 583 if (condition) 584 do_something_completely_different(); 585 586 if (x == y) { 587 q(); 588 } else if (x > y) { 589 w(); 590 } else { 591 r(); 592 } 593 } 594 595A style similar to the default Visual Studio formatting style: 596 597.. code-block:: yaml 598 599 UseTab: Never 600 IndentWidth: 4 601 BreakBeforeBraces: Allman 602 AllowShortIfStatementsOnASingleLine: false 603 IndentCaseLabels: false 604 ColumnLimit: 0 605 606The result is: 607 608.. code-block:: c++ 609 610 void test() 611 { 612 switch (suffix) 613 { 614 case 0: 615 case 1: 616 do_something(); 617 break; 618 case 2: 619 do_something_else(); 620 break; 621 default: 622 break; 623 } 624 if (condition) 625 do_somthing_completely_different(); 626 627 if (x == y) 628 { 629 q(); 630 } 631 else if (x > y) 632 { 633 w(); 634 } 635 else 636 { 637 r(); 638 } 639 } 640 641