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