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