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
159  .. code-block:: c++
160
161    someLongFunction(argument1,
162                     argument2);
163
164**AlignConsecutiveAssignments** (``bool``)
165  If ``true``, aligns consecutive assignments.
166
167  This will align the assignment operators of consecutive lines. This
168  will result in formattings like
169
170  .. code-block:: c++
171
172    int aaaa = 12;
173    int b    = 23;
174    int ccc  = 23;
175
176**AlignConsecutiveDeclarations** (``bool``)
177  If ``true``, aligns consecutive declarations.
178
179  This will align the declaration names of consecutive lines. This
180  will result in formattings like
181
182  .. code-block:: c++
183
184    int         aaaa = 12;
185    float       b = 23;
186    std::string ccc = 23;
187
188**AlignEscapedNewlinesLeft** (``bool``)
189  If ``true``, aligns escaped newlines as far left as possible.
190  Otherwise puts them into the right-most column.
191
192**AlignOperands** (``bool``)
193  If ``true``, horizontally align operands of binary and ternary
194  expressions.
195
196**AlignTrailingComments** (``bool``)
197  If ``true``, aligns trailing comments.
198
199**AllowAllParametersOfDeclarationOnNextLine** (``bool``)
200  Allow putting all parameters of a function declaration onto
201  the next line even if ``BinPackParameters`` is ``false``.
202
203**AllowShortBlocksOnASingleLine** (``bool``)
204  Allows contracting simple braced statements to a single line.
205
206  E.g., this allows ``if (a) { return; }`` to be put on a single line.
207
208**AllowShortCaseLabelsOnASingleLine** (``bool``)
209  If ``true``, short case labels will be contracted to a single line.
210
211**AllowShortFunctionsOnASingleLine** (``ShortFunctionStyle``)
212  Dependent on the value, ``int f() { return 0; }`` can be put
213  on a single line.
214
215  Possible values:
216
217  * ``SFS_None`` (in configuration: ``None``)
218    Never merge functions into a single line.
219  * ``SFS_Empty`` (in configuration: ``Empty``)
220    Only merge empty functions.
221  * ``SFS_Inline`` (in configuration: ``Inline``)
222    Only merge functions defined inside a class. Implies "empty".
223  * ``SFS_All`` (in configuration: ``All``)
224    Merge all functions fitting on a single line.
225
226
227**AllowShortIfStatementsOnASingleLine** (``bool``)
228  If ``true``, ``if (a) return;`` can be put on a single
229  line.
230
231**AllowShortLoopsOnASingleLine** (``bool``)
232  If ``true``, ``while (true) continue;`` can be put on a
233  single line.
234
235**AlwaysBreakAfterDefinitionReturnType** (``DefinitionReturnTypeBreakingStyle``)
236  The function definition return type breaking style to use.
237
238  Possible values:
239
240  * ``DRTBS_None`` (in configuration: ``None``)
241    Break after return type automatically.
242    ``PenaltyReturnTypeOnItsOwnLine`` is taken into account.
243  * ``DRTBS_All`` (in configuration: ``All``)
244    Always break after the return type.
245  * ``DRTBS_TopLevel`` (in configuration: ``TopLevel``)
246    Always break after the return types of top level functions.
247
248
249**AlwaysBreakBeforeMultilineStrings** (``bool``)
250  If ``true``, always break before multiline string literals.
251
252  This flag is mean to make cases where there are multiple multiline strings
253  in a file look more consistent. Thus, it will only take effect if wrapping
254  the string at that point leads to it being indented
255  ``ContinuationIndentWidth`` spaces from the start of the line.
256
257**AlwaysBreakTemplateDeclarations** (``bool``)
258  If ``true``, always break after the ``template<...>`` of a
259  template declaration.
260
261**BinPackArguments** (``bool``)
262  If ``false``, a function call's arguments will either be all on the
263  same line or will have one line each.
264
265**BinPackParameters** (``bool``)
266  If ``false``, a function declaration's or function definition's
267  parameters will either all be on the same line or will have one line each.
268
269**BraceWrapping** (``BraceWrappingFlags``)
270  Control of individual brace wrapping cases.
271
272  If ``BreakBeforeBraces`` is set to ``custom``, use this to specify how each
273  individual brace case should be handled. Otherwise, this is ignored.
274
275  Nested configuration flags:
276
277  * ``bool AfterClass`` Wrap class definitions.
278  * ``bool AfterControlStatement`` Wrap control statements (if/for/while/switch/..).
279  * ``bool AfterEnum`` Wrap enum definitions.
280  * ``bool AfterFunction`` Wrap function definitions.
281  * ``bool AfterNamespace`` Wrap namespace definitions.
282  * ``bool AfterObjCDeclaration`` Wrap ObjC definitions (@autoreleasepool, interfaces, ..).
283  * ``bool AfterStruct`` Wrap struct definitions.
284  * ``bool AfterUnion`` Wrap union definitions.
285  * ``bool BeforeCatch`` Wrap before ``catch``.
286  * ``bool BeforeElse`` Wrap before ``else``.
287  * ``bool IndentBraces`` Indent the wrapped braces themselves.
288
289
290**BreakBeforeBinaryOperators** (``BinaryOperatorStyle``)
291  The way to wrap binary operators.
292
293  Possible values:
294
295  * ``BOS_None`` (in configuration: ``None``)
296    Break after operators.
297  * ``BOS_NonAssignment`` (in configuration: ``NonAssignment``)
298    Break before operators that aren't assignments.
299  * ``BOS_All`` (in configuration: ``All``)
300    Break before operators.
301
302
303**BreakBeforeBraces** (``BraceBreakingStyle``)
304  The brace breaking style to use.
305
306  Possible values:
307
308  * ``BS_Attach`` (in configuration: ``Attach``)
309    Always attach braces to surrounding context.
310  * ``BS_Linux`` (in configuration: ``Linux``)
311    Like ``Attach``, but break before braces on function, namespace and
312    class definitions.
313  * ``BS_Mozilla`` (in configuration: ``Mozilla``)
314    Like ``Attach``, but break before braces on enum, function, and record
315    definitions.
316  * ``BS_Stroustrup`` (in configuration: ``Stroustrup``)
317    Like ``Attach``, but break before function definitions, 'catch', and 'else'.
318  * ``BS_Allman`` (in configuration: ``Allman``)
319    Always break before braces.
320  * ``BS_GNU`` (in configuration: ``GNU``)
321    Always break before braces and add an extra level of indentation to
322    braces of control statements, not to those of class, function
323    or other definitions.
324  * ``BS_WebKit`` (in configuration: ``WebKit``)
325    Like ``Attach``, but break before functions.
326  * ``BS_Custom`` (in configuration: ``Custom``)
327    Configure each individual brace in ``BraceWrapping``.
328
329
330**BreakBeforeTernaryOperators** (``bool``)
331  If ``true``, ternary operators will be placed after line breaks.
332
333**BreakConstructorInitializersBeforeComma** (``bool``)
334  Always break constructor initializers before commas and align
335  the commas with the colon.
336
337**ColumnLimit** (``unsigned``)
338  The column limit.
339
340  A column limit of ``0`` means that there is no column limit. In this case,
341  clang-format will respect the input's line breaking decisions within
342  statements unless they contradict other rules.
343
344**CommentPragmas** (``std::string``)
345  A regular expression that describes comments with special meaning,
346  which should not be split into lines or otherwise changed.
347
348**ConstructorInitializerAllOnOneLineOrOnePerLine** (``bool``)
349  If the constructor initializers don't fit on a line, put each
350  initializer on its own line.
351
352**ConstructorInitializerIndentWidth** (``unsigned``)
353  The number of characters to use for indentation of constructor
354  initializer lists.
355
356**ContinuationIndentWidth** (``unsigned``)
357  Indent width for line continuations.
358
359**Cpp11BracedListStyle** (``bool``)
360  If ``true``, format braced lists as best suited for C++11 braced
361  lists.
362
363  Important differences:
364  - No spaces inside the braced list.
365  - No line break before the closing brace.
366  - Indentation with the continuation indent, not with the block indent.
367
368  Fundamentally, C++11 braced lists are formatted exactly like function
369  calls would be formatted in their place. If the braced list follows a name
370  (e.g. a type or variable name), clang-format formats as if the ``{}`` were
371  the parentheses of a function call with that name. If there is no name,
372  a zero-length name is assumed.
373
374**DerivePointerAlignment** (``bool``)
375  If ``true``, analyze the formatted file for the most common
376  alignment of & and \*. ``PointerAlignment`` is then used only as fallback.
377
378**DisableFormat** (``bool``)
379  Disables formatting completely.
380
381**ExperimentalAutoDetectBinPacking** (``bool``)
382  If ``true``, clang-format detects whether function calls and
383  definitions are formatted with one parameter per line.
384
385  Each call can be bin-packed, one-per-line or inconclusive. If it is
386  inconclusive, e.g. completely on one line, but a decision needs to be
387  made, clang-format analyzes whether there are other bin-packed cases in
388  the input file and act accordingly.
389
390  NOTE: This is an experimental flag, that might go away or be renamed. Do
391  not use this in config files, etc. Use at your own risk.
392
393**ForEachMacros** (``std::vector<std::string>``)
394  A vector of macros that should be interpreted as foreach loops
395  instead of as function calls.
396
397  These are expected to be macros of the form:
398
399  .. code-block:: c++
400
401    FOREACH(<variable-declaration>, ...)
402      <loop-body>
403
404  In the .clang-format configuration file, this can be configured like:
405
406  .. code-block:: c++
407
408    ForEachMacros: ['RANGES_FOR', 'FOREACH']
409
410  For example: BOOST_FOREACH.
411
412**IncludeCategories** (``std::vector<IncludeCategory>``)
413  Regular expressions denoting the different #include categories used
414  for ordering #includes.
415
416  These regular expressions are matched against the filename of an include
417  (including the <> or "") in order. The value belonging to the first
418  matching regular expression is assigned and #includes are sorted first
419  according to increasing category number and then alphabetically within
420  each category.
421
422  If none of the regular expressions match, UINT_MAX is assigned as
423  category. The main header for a source file automatically gets category 0,
424  so that it is kept at the beginning of the #includes
425  (http://llvm.org/docs/CodingStandards.html#include-style).
426
427  To configure this in the .clang-format file, use:
428
429  .. code-block:: c++
430
431    IncludeCategories:
432      - Regex:           '^"(llvm|llvm-c|clang|clang-c)/'
433        Priority:        2
434      - Regex:           '^(<|"(gtest|isl|json)/)'
435        Priority:        3
436      - Regex:           '.\*'
437        Priority:        1
438
439**IndentCaseLabels** (``bool``)
440  Indent case labels one level from the switch statement.
441
442  When ``false``, use the same indentation level as for the switch statement.
443  Switch statement body is always indented one level more than case labels.
444
445**IndentWidth** (``unsigned``)
446  The number of columns to use for indentation.
447
448**IndentWrappedFunctionNames** (``bool``)
449  Indent if a function definition or declaration is wrapped after the
450  type.
451
452**KeepEmptyLinesAtTheStartOfBlocks** (``bool``)
453  If true, empty lines at the start of blocks are kept.
454
455**Language** (``LanguageKind``)
456  Language, this format style is targeted at.
457
458  Possible values:
459
460  * ``LK_None`` (in configuration: ``None``)
461    Do not use.
462  * ``LK_Cpp`` (in configuration: ``Cpp``)
463    Should be used for C, C++, ObjectiveC, ObjectiveC++.
464  * ``LK_Java`` (in configuration: ``Java``)
465    Should be used for Java.
466  * ``LK_JavaScript`` (in configuration: ``JavaScript``)
467    Should be used for JavaScript.
468  * ``LK_Proto`` (in configuration: ``Proto``)
469    Should be used for Protocol Buffers
470    (https://developers.google.com/protocol-buffers/).
471
472
473**MacroBlockBegin** (``std::string``)
474  A regular expression matching macros that start a block.
475
476**MacroBlockEnd** (``std::string``)
477  A regular expression matching macros that end a block.
478
479**MaxEmptyLinesToKeep** (``unsigned``)
480  The maximum number of consecutive empty lines to keep.
481
482**NamespaceIndentation** (``NamespaceIndentationKind``)
483  The indentation used for namespaces.
484
485  Possible values:
486
487  * ``NI_None`` (in configuration: ``None``)
488    Don't indent in namespaces.
489  * ``NI_Inner`` (in configuration: ``Inner``)
490    Indent only in inner namespaces (nested in other namespaces).
491  * ``NI_All`` (in configuration: ``All``)
492    Indent in all namespaces.
493
494
495**ObjCBlockIndentWidth** (``unsigned``)
496  The number of characters to use for indentation of ObjC blocks.
497
498**ObjCSpaceAfterProperty** (``bool``)
499  Add a space after ``@property`` in Objective-C, i.e. use
500  ``\@property (readonly)`` instead of ``\@property(readonly)``.
501
502**ObjCSpaceBeforeProtocolList** (``bool``)
503  Add a space in front of an Objective-C protocol list, i.e. use
504  ``Foo <Protocol>`` instead of ``Foo<Protocol>``.
505
506**PenaltyBreakBeforeFirstCallParameter** (``unsigned``)
507  The penalty for breaking a function call after "call(".
508
509**PenaltyBreakComment** (``unsigned``)
510  The penalty for each line break introduced inside a comment.
511
512**PenaltyBreakFirstLessLess** (``unsigned``)
513  The penalty for breaking before the first ``<<``.
514
515**PenaltyBreakString** (``unsigned``)
516  The penalty for each line break introduced inside a string literal.
517
518**PenaltyExcessCharacter** (``unsigned``)
519  The penalty for each character outside of the column limit.
520
521**PenaltyReturnTypeOnItsOwnLine** (``unsigned``)
522  Penalty for putting the return type of a function onto its own
523  line.
524
525**PointerAlignment** (``PointerAlignmentStyle``)
526  Pointer and reference alignment style.
527
528  Possible values:
529
530  * ``PAS_Left`` (in configuration: ``Left``)
531    Align pointer to the left.
532  * ``PAS_Right`` (in configuration: ``Right``)
533    Align pointer to the right.
534  * ``PAS_Middle`` (in configuration: ``Middle``)
535    Align pointer in the middle.
536
537
538**SpaceAfterCStyleCast** (``bool``)
539  If ``true``, a space may be inserted after C style casts.
540
541**SpaceBeforeAssignmentOperators** (``bool``)
542  If ``false``, spaces will be removed before assignment operators.
543
544**SpaceBeforeParens** (``SpaceBeforeParensOptions``)
545  Defines in which cases to put a space before opening parentheses.
546
547  Possible values:
548
549  * ``SBPO_Never`` (in configuration: ``Never``)
550    Never put a space before opening parentheses.
551  * ``SBPO_ControlStatements`` (in configuration: ``ControlStatements``)
552    Put a space before opening parentheses only after control statement
553    keywords (``for/if/while...``).
554  * ``SBPO_Always`` (in configuration: ``Always``)
555    Always put a space before opening parentheses, except when it's
556    prohibited by the syntax rules (in function-like macro definitions) or
557    when determined by other style rules (after unary operators, opening
558    parentheses, etc.)
559
560
561**SpaceInEmptyParentheses** (``bool``)
562  If ``true``, spaces may be inserted into '()'.
563
564**SpacesBeforeTrailingComments** (``unsigned``)
565  The number of spaces before trailing line comments
566  (``//`` - comments).
567
568  This does not affect trailing block comments (``/**/`` - comments) as those
569  commonly have different usage patterns and a number of special cases.
570
571**SpacesInAngles** (``bool``)
572  If ``true``, spaces will be inserted after '<' and before '>' in
573  template argument lists
574
575**SpacesInCStyleCastParentheses** (``bool``)
576  If ``true``, spaces may be inserted into C style casts.
577
578**SpacesInContainerLiterals** (``bool``)
579  If ``true``, spaces are inserted inside container literals (e.g.
580  ObjC and Javascript array and dict literals).
581
582**SpacesInParentheses** (``bool``)
583  If ``true``, spaces will be inserted after '(' and before ')'.
584
585**SpacesInSquareBrackets** (``bool``)
586  If ``true``, spaces will be inserted after '[' and before ']'.
587
588**Standard** (``LanguageStandard``)
589  Format compatible with this standard, e.g. use
590  ``A<A<int> >`` instead of ``A<A<int>>`` for LS_Cpp03.
591
592  Possible values:
593
594  * ``LS_Cpp03`` (in configuration: ``Cpp03``)
595    Use C++03-compatible syntax.
596  * ``LS_Cpp11`` (in configuration: ``Cpp11``)
597    Use features of C++11 (e.g. ``A<A<int>>`` instead of
598    ``A<A<int> >``).
599  * ``LS_Auto`` (in configuration: ``Auto``)
600    Automatic detection based on the input.
601
602
603**TabWidth** (``unsigned``)
604  The number of columns used for tab stops.
605
606**UseTab** (``UseTabStyle``)
607  The way to use tab characters in the resulting file.
608
609  Possible values:
610
611  * ``UT_Never`` (in configuration: ``Never``)
612    Never use tab.
613  * ``UT_ForIndentation`` (in configuration: ``ForIndentation``)
614    Use tabs only for indentation.
615  * ``UT_Always`` (in configuration: ``Always``)
616    Use tabs whenever we need to fill whitespace that spans at least from
617    one tab stop to the next one.
618
619
620.. END_FORMAT_STYLE_OPTIONS
621
622Adding additional style options
623===============================
624
625Each additional style option adds costs to the clang-format project. Some of
626these costs affect the clang-format developement itself, as we need to make
627sure that any given combination of options work and that new features don't
628break any of the existing options in any way. There are also costs for end users
629as options become less discoverable and people have to think about and make a
630decision on options they don't really care about.
631
632The goal of the clang-format project is more on the side of supporting a
633limited set of styles really well as opposed to supporting every single style
634used by a codebase somewhere in the wild. Of course, we do want to support all
635major projects and thus have established the following bar for adding style
636options. Each new style option must ..
637
638  * be used in a project of significant size (have dozens of contributors)
639  * have a publicly accessible style guide
640  * have a person willing to contribute and maintain patches
641
642Examples
643========
644
645A style similar to the `Linux Kernel style
646<https://www.kernel.org/doc/Documentation/CodingStyle>`_:
647
648.. code-block:: yaml
649
650  BasedOnStyle: LLVM
651  IndentWidth: 8
652  UseTab: Always
653  BreakBeforeBraces: Linux
654  AllowShortIfStatementsOnASingleLine: false
655  IndentCaseLabels: false
656
657The result is (imagine that tabs are used for indentation here):
658
659.. code-block:: c++
660
661  void test()
662  {
663          switch (x) {
664          case 0:
665          case 1:
666                  do_something();
667                  break;
668          case 2:
669                  do_something_else();
670                  break;
671          default:
672                  break;
673          }
674          if (condition)
675                  do_something_completely_different();
676
677          if (x == y) {
678                  q();
679          } else if (x > y) {
680                  w();
681          } else {
682                  r();
683          }
684  }
685
686A style similar to the default Visual Studio formatting style:
687
688.. code-block:: yaml
689
690  UseTab: Never
691  IndentWidth: 4
692  BreakBeforeBraces: Allman
693  AllowShortIfStatementsOnASingleLine: false
694  IndentCaseLabels: false
695  ColumnLimit: 0
696
697The result is:
698
699.. code-block:: c++
700
701  void test()
702  {
703      switch (suffix)
704      {
705      case 0:
706      case 1:
707          do_something();
708          break;
709      case 2:
710          do_something_else();
711          break;
712      default:
713          break;
714      }
715      if (condition)
716          do_somthing_completely_different();
717
718      if (x == y)
719      {
720          q();
721      }
722      else if (x > y)
723      {
724          w();
725      }
726      else
727      {
728          r();
729      }
730  }
731
732