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