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** (``bool``) 222 If ``true``, always break after function definition return types. 223 224 More truthfully called 'break before the identifier following the type 225 in a function definition'. PenaltyReturnTypeOnItsOwnLine becomes 226 irrelevant. 227 228**AlwaysBreakBeforeMultilineStrings** (``bool``) 229 If ``true``, always break before multiline string literals. 230 231 This flag is mean to make cases where there are multiple multiline strings 232 in a file look more consistent. Thus, it will only take effect if wrapping 233 the string at that point leads to it being indented 234 ``ContinuationIndentWidth`` spaces from the start of the line. 235 236**AlwaysBreakTemplateDeclarations** (``bool``) 237 If ``true``, always break after the ``template<...>`` of a 238 template declaration. 239 240**BinPackArguments** (``bool``) 241 If ``false``, a function call's arguments will either be all on the 242 same line or will have one line each. 243 244**BinPackParameters** (``bool``) 245 If ``false``, a function declaration's or function definition's 246 parameters will either all be on the same line or will have one line each. 247 248**BreakBeforeBinaryOperators** (``BinaryOperatorStyle``) 249 The way to wrap binary operators. 250 251 Possible values: 252 253 * ``BOS_None`` (in configuration: ``None``) 254 Break after operators. 255 * ``BOS_NonAssignment`` (in configuration: ``NonAssignment``) 256 Break before operators that aren't assignments. 257 * ``BOS_All`` (in configuration: ``All``) 258 Break before operators. 259 260 261**BreakBeforeBraces** (``BraceBreakingStyle``) 262 The brace breaking style to use. 263 264 Possible values: 265 266 * ``BS_Attach`` (in configuration: ``Attach``) 267 Always attach braces to surrounding context. 268 * ``BS_Linux`` (in configuration: ``Linux``) 269 Like ``Attach``, but break before braces on function, namespace and 270 class definitions. 271 * ``BS_Stroustrup`` (in configuration: ``Stroustrup``) 272 Like ``Attach``, but break before function definitions, and 'else'. 273 * ``BS_Allman`` (in configuration: ``Allman``) 274 Always break before braces. 275 * ``BS_GNU`` (in configuration: ``GNU``) 276 Always break before braces and add an extra level of indentation to 277 braces of control statements, not to those of class, function 278 or other definitions. 279 280 281**BreakBeforeTernaryOperators** (``bool``) 282 If ``true``, ternary operators will be placed after line breaks. 283 284**BreakConstructorInitializersBeforeComma** (``bool``) 285 Always break constructor initializers before commas and align 286 the commas with the colon. 287 288**ColumnLimit** (``unsigned``) 289 The column limit. 290 291 A column limit of ``0`` means that there is no column limit. In this case, 292 clang-format will respect the input's line breaking decisions within 293 statements unless they contradict other rules. 294 295**CommentPragmas** (``std::string``) 296 A regular expression that describes comments with special meaning, 297 which should not be split into lines or otherwise changed. 298 299**ConstructorInitializerAllOnOneLineOrOnePerLine** (``bool``) 300 If the constructor initializers don't fit on a line, put each 301 initializer on its own line. 302 303**ConstructorInitializerIndentWidth** (``unsigned``) 304 The number of characters to use for indentation of constructor 305 initializer lists. 306 307**ContinuationIndentWidth** (``unsigned``) 308 Indent width for line continuations. 309 310**Cpp11BracedListStyle** (``bool``) 311 If ``true``, format braced lists as best suited for C++11 braced 312 lists. 313 314 Important differences: 315 - No spaces inside the braced list. 316 - No line break before the closing brace. 317 - Indentation with the continuation indent, not with the block indent. 318 319 Fundamentally, C++11 braced lists are formatted exactly like function 320 calls would be formatted in their place. If the braced list follows a name 321 (e.g. a type or variable name), clang-format formats as if the ``{}`` were 322 the parentheses of a function call with that name. If there is no name, 323 a zero-length name is assumed. 324 325**DerivePointerAlignment** (``bool``) 326 If ``true``, analyze the formatted file for the most common 327 alignment of & and \*. ``PointerAlignment`` is then used only as fallback. 328 329**DisableFormat** (``bool``) 330 Disables formatting at all. 331 332**ExperimentalAutoDetectBinPacking** (``bool``) 333 If ``true``, clang-format detects whether function calls and 334 definitions are formatted with one parameter per line. 335 336 Each call can be bin-packed, one-per-line or inconclusive. If it is 337 inconclusive, e.g. completely on one line, but a decision needs to be 338 made, clang-format analyzes whether there are other bin-packed cases in 339 the input file and act accordingly. 340 341 NOTE: This is an experimental flag, that might go away or be renamed. Do 342 not use this in config files, etc. Use at your own risk. 343 344**ForEachMacros** (``std::vector<std::string>``) 345 A vector of macros that should be interpreted as foreach loops 346 instead of as function calls. 347 348 These are expected to be macros of the form: 349 \code 350 FOREACH(<variable-declaration>, ...) 351 <loop-body> 352 \endcode 353 354 For example: BOOST_FOREACH. 355 356**IndentCaseLabels** (``bool``) 357 Indent case labels one level from the switch statement. 358 359 When ``false``, use the same indentation level as for the switch statement. 360 Switch statement body is always indented one level more than case labels. 361 362**IndentWidth** (``unsigned``) 363 The number of columns to use for indentation. 364 365**IndentWrappedFunctionNames** (``bool``) 366 Indent if a function definition or declaration is wrapped after the 367 type. 368 369**KeepEmptyLinesAtTheStartOfBlocks** (``bool``) 370 If true, empty lines at the start of blocks are kept. 371 372**Language** (``LanguageKind``) 373 Language, this format style is targeted at. 374 375 Possible values: 376 377 * ``LK_None`` (in configuration: ``None``) 378 Do not use. 379 * ``LK_Cpp`` (in configuration: ``Cpp``) 380 Should be used for C, C++, ObjectiveC, ObjectiveC++. 381 * ``LK_Java`` (in configuration: ``Java``) 382 Should be used for Java. 383 * ``LK_JavaScript`` (in configuration: ``JavaScript``) 384 Should be used for JavaScript. 385 * ``LK_Proto`` (in configuration: ``Proto``) 386 Should be used for Protocol Buffers 387 (https://developers.google.com/protocol-buffers/). 388 389 390**MaxEmptyLinesToKeep** (``unsigned``) 391 The maximum number of consecutive empty lines to keep. 392 393**NamespaceIndentation** (``NamespaceIndentationKind``) 394 The indentation used for namespaces. 395 396 Possible values: 397 398 * ``NI_None`` (in configuration: ``None``) 399 Don't indent in namespaces. 400 * ``NI_Inner`` (in configuration: ``Inner``) 401 Indent only in inner namespaces (nested in other namespaces). 402 * ``NI_All`` (in configuration: ``All``) 403 Indent in all namespaces. 404 405 406**ObjCBlockIndentWidth** (``unsigned``) 407 The number of characters to use for indentation of ObjC blocks. 408 409**ObjCSpaceAfterProperty** (``bool``) 410 Add a space after ``@property`` in Objective-C, i.e. use 411 ``\@property (readonly)`` instead of ``\@property(readonly)``. 412 413**ObjCSpaceBeforeProtocolList** (``bool``) 414 Add a space in front of an Objective-C protocol list, i.e. use 415 ``Foo <Protocol>`` instead of ``Foo<Protocol>``. 416 417**PenaltyBreakBeforeFirstCallParameter** (``unsigned``) 418 The penalty for breaking a function call after "call(". 419 420**PenaltyBreakComment** (``unsigned``) 421 The penalty for each line break introduced inside a comment. 422 423**PenaltyBreakFirstLessLess** (``unsigned``) 424 The penalty for breaking before the first ``<<``. 425 426**PenaltyBreakString** (``unsigned``) 427 The penalty for each line break introduced inside a string literal. 428 429**PenaltyExcessCharacter** (``unsigned``) 430 The penalty for each character outside of the column limit. 431 432**PenaltyReturnTypeOnItsOwnLine** (``unsigned``) 433 Penalty for putting the return type of a function onto its own 434 line. 435 436**PointerAlignment** (``PointerAlignmentStyle``) 437 Pointer and reference alignment style. 438 439 Possible values: 440 441 * ``PAS_Left`` (in configuration: ``Left``) 442 Align pointer to the left. 443 * ``PAS_Right`` (in configuration: ``Right``) 444 Align pointer to the right. 445 * ``PAS_Middle`` (in configuration: ``Middle``) 446 Align pointer in the middle. 447 448 449**SpaceAfterCStyleCast** (``bool``) 450 If ``true``, a space may be inserted after C style casts. 451 452**SpaceBeforeAssignmentOperators** (``bool``) 453 If ``false``, spaces will be removed before assignment operators. 454 455**SpaceBeforeParens** (``SpaceBeforeParensOptions``) 456 Defines in which cases to put a space before opening parentheses. 457 458 Possible values: 459 460 * ``SBPO_Never`` (in configuration: ``Never``) 461 Never put a space before opening parentheses. 462 * ``SBPO_ControlStatements`` (in configuration: ``ControlStatements``) 463 Put a space before opening parentheses only after control statement 464 keywords (``for/if/while...``). 465 * ``SBPO_Always`` (in configuration: ``Always``) 466 Always put a space before opening parentheses, except when it's 467 prohibited by the syntax rules (in function-like macro definitions) or 468 when determined by other style rules (after unary operators, opening 469 parentheses, etc.) 470 471 472**SpaceInEmptyParentheses** (``bool``) 473 If ``true``, spaces may be inserted into '()'. 474 475**SpacesBeforeTrailingComments** (``unsigned``) 476 The number of spaces before trailing line comments 477 (``//`` - comments). 478 479 This does not affect trailing block comments (``/**/`` - comments) as those 480 commonly have different usage patterns and a number of special cases. 481 482**SpacesInAngles** (``bool``) 483 If ``true``, spaces will be inserted after '<' and before '>' in 484 template argument lists 485 486**SpacesInCStyleCastParentheses** (``bool``) 487 If ``true``, spaces may be inserted into C style casts. 488 489**SpacesInContainerLiterals** (``bool``) 490 If ``true``, spaces are inserted inside container literals (e.g. 491 ObjC and Javascript array and dict literals). 492 493**SpacesInParentheses** (``bool``) 494 If ``true``, spaces will be inserted after '(' and before ')'. 495 496**SpacesInSquareBrackets** (``bool``) 497 If ``true``, spaces will be inserted after '[' and before ']'. 498 499**Standard** (``LanguageStandard``) 500 Format compatible with this standard, e.g. use 501 ``A<A<int> >`` instead of ``A<A<int>>`` for LS_Cpp03. 502 503 Possible values: 504 505 * ``LS_Cpp03`` (in configuration: ``Cpp03``) 506 Use C++03-compatible syntax. 507 * ``LS_Cpp11`` (in configuration: ``Cpp11``) 508 Use features of C++11 (e.g. ``A<A<int>>`` instead of 509 ``A<A<int> >``). 510 * ``LS_Auto`` (in configuration: ``Auto``) 511 Automatic detection based on the input. 512 513 514**TabWidth** (``unsigned``) 515 The number of columns used for tab stops. 516 517**UseTab** (``UseTabStyle``) 518 The way to use tab characters in the resulting file. 519 520 Possible values: 521 522 * ``UT_Never`` (in configuration: ``Never``) 523 Never use tab. 524 * ``UT_ForIndentation`` (in configuration: ``ForIndentation``) 525 Use tabs only for indentation. 526 * ``UT_Always`` (in configuration: ``Always``) 527 Use tabs whenever we need to fill whitespace that spans at least from 528 one tab stop to the next one. 529 530 531.. END_FORMAT_STYLE_OPTIONS 532 533Examples 534======== 535 536A style similar to the `Linux Kernel style 537<https://www.kernel.org/doc/Documentation/CodingStyle>`_: 538 539.. code-block:: yaml 540 541 BasedOnStyle: LLVM 542 IndentWidth: 8 543 UseTab: Always 544 BreakBeforeBraces: Linux 545 AllowShortIfStatementsOnASingleLine: false 546 IndentCaseLabels: false 547 548The result is (imagine that tabs are used for indentation here): 549 550.. code-block:: c++ 551 552 void test() 553 { 554 switch (x) { 555 case 0: 556 case 1: 557 do_something(); 558 break; 559 case 2: 560 do_something_else(); 561 break; 562 default: 563 break; 564 } 565 if (condition) 566 do_something_completely_different(); 567 568 if (x == y) { 569 q(); 570 } else if (x > y) { 571 w(); 572 } else { 573 r(); 574 } 575 } 576 577A style similar to the default Visual Studio formatting style: 578 579.. code-block:: yaml 580 581 UseTab: Never 582 IndentWidth: 4 583 BreakBeforeBraces: Allman 584 AllowShortIfStatementsOnASingleLine: false 585 IndentCaseLabels: false 586 ColumnLimit: 0 587 588The result is: 589 590.. code-block:: c++ 591 592 void test() 593 { 594 switch (suffix) 595 { 596 case 0: 597 case 1: 598 do_something(); 599 break; 600 case 2: 601 do_something_else(); 602 break; 603 default: 604 break; 605 } 606 if (condition) 607 do_somthing_completely_different(); 608 609 if (x == y) 610 { 611 q(); 612 } 613 else if (x > y) 614 { 615 w(); 616 } 617 else 618 { 619 r(); 620 } 621 } 622 623