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