Clang-Format Style Options — Clang 21.0.0git documentation (original) (raw)

Clang-Format Style Options describes configurable formatting style options supported by LibFormat and ClangFormat.

When using clang-format command line utility orclang::format::reformat(...) functions from code, one can either use one of the predefined styles (LLVM, Google, Chromium, Mozilla, WebKit, Microsoft) or create a custom style by configuring specific style options.

Configuring Style with clang-format

clang-format supports two ways to provide custom style options: directly specify style configuration in the -style= command line option or use -style=file and put style configuration in the .clang-format or_clang-format file in the project directory.

When using -style=file, clang-format for each input file will try to find the .clang-format file located in the closest parent directory of the input file. When the standard input is used, the search is started from the current directory.

When using -style=file:<format_file_path>, clang-format for each input file will use the format file located at <format_file_path>. The path may be absolute or relative to the working directory.

The .clang-format file uses YAML format:

key1: value1 key2: value2

A comment.

...

The configuration file can consist of several sections each having differentLanguage: parameter denoting the programming language this section of the configuration is targeted at. See the description of the Language option below for the list of supported languages. The first section may have no language set, it will set the default style options for all languages. Configuration sections for specific language will override options set in the default section.

When clang-format formats a file, it auto-detects the language using the file name. When formatting standard input or a file that doesn’t have the extension corresponding to its language, -assume-filename= option can be used to override the file name clang-format uses to detect the language.

An example of a configuration file for multiple languages:


We'll use defaults from the LLVM style, but with 4 columns indentation.

BasedOnStyle: LLVM IndentWidth: 4

Language: Cpp # Force pointers to the type for C++. DerivePointerAlignment: false PointerAlignment: Left

Language: JavaScript # Use 100 columns for JS. ColumnLimit: 100

Language: Proto # Don't format .proto files. DisableFormat: true

Language: CSharp

Use 100 columns for C#.

ColumnLimit: 100 ...

An easy way to get a valid .clang-format file containing all configuration options of a certain predefined style is:

clang-format -style=llvm -dump-config > .clang-format

When specifying configuration in the -style= option, the same configuration is applied for all input files. The format of the configuration is:

-style='{key1: value1, key2: value2, ...}'

Disabling Formatting on a Piece of Code

Clang-format understands also special comments that switch formatting in a delimited range. The code between a comment // clang-format off or/* clang-format off */ up to a comment // clang-format on or/* clang-format on */ will not be formatted. The comments themselves will be formatted (aligned) normally. Also, a colon (:) and additional text may follow // clang-format off or // clang-format on to explain why clang-format is turned off or back on.

int formatted_code; // clang-format off void unformatted_code ; // clang-format on void formatted_code_again;

Configuring Style in Code

When using clang::format::reformat(...) functions, the format is specified by supplying the clang::format::FormatStylestructure.

Configurable Format Style Options

This section lists the supported style options. Value type is specified for each option. For enumeration types possible values are specified both as a C++ enumeration member (with a prefix, e.g. LS_Auto), and as a value usable in the configuration (without a prefix: Auto).

BasedOnStyle (String)

The style used for all options not specifically set in the configuration.

This option is supported only in the clang-format configuration (both within -style='{...}' and the .clang-format file).

Possible values:

AccessModifierOffset (Integer) clang-format 3.3

The extra indent or outdent of access modifiers, e.g. public:.

AlignAfterOpenBracket (BracketAlignmentStyle) clang-format 3.8

If true, horizontally aligns arguments after an open bracket.

This applies to round brackets (parentheses), angle brackets and square brackets.

Possible values:

AlignArrayOfStructures (ArrayInitializerAlignmentStyle) clang-format 13

If not None, when using initialization for an array of structs aligns the fields into columns.

Note

As of clang-format 15 this option only applied to arrays with equal number of columns per row.

Possible values:

AlignConsecutiveAssignments (AlignConsecutiveStyle) clang-format 3.8

Style of aligning consecutive assignments.

Consecutive will result in formattings like:

int a = 1; int somelongname = 2; double c = 3;

Nested configuration flags:

Alignment options.

They can also be read as a whole for compatibility. The choices are:

For example, to align across empty lines and not across comments, either of these work.

AlignConsecutiveAssignments: AcrossEmptyLines

AlignConsecutiveAssignments: Enabled: true AcrossEmptyLines: true AcrossComments: false

#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
#define bar(y, z) (y + z)
int a = 1;
int somelongname = 2;
double c = 3;
int aaaa : 1;
int b : 12;
int ccc : 8;
int aaaa = 12;
float b = 23;
std::string ccc;

bbb >>= 2;
false:
a >>= 2;
bbb = 2;
a = 2;
bbb >>= 2;

AlignConsecutiveBitFields (AlignConsecutiveStyle) clang-format 11

Style of aligning consecutive bit fields.

Consecutive will align the bitfield separators of consecutive lines. This will result in formattings like:

int aaaa : 1; int b : 12; int ccc : 8;

Nested configuration flags:

Alignment options.

They can also be read as a whole for compatibility. The choices are:

For example, to align across empty lines and not across comments, either of these work.

AlignConsecutiveBitFields: AcrossEmptyLines

AlignConsecutiveBitFields: Enabled: true AcrossEmptyLines: true AcrossComments: false

#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
#define bar(y, z) (y + z)
int a = 1;
int somelongname = 2;
double c = 3;
int aaaa : 1;
int b : 12;
int ccc : 8;
int aaaa = 12;
float b = 23;
std::string ccc;

bbb >>= 2;
false:
a >>= 2;
bbb = 2;
a = 2;
bbb >>= 2;

AlignConsecutiveDeclarations (AlignConsecutiveStyle) clang-format 3.8

Style of aligning consecutive declarations.

Consecutive will align the declaration names of consecutive lines. This will result in formattings like:

int aaaa = 12; float b = 23; std::string ccc;

Nested configuration flags:

Alignment options.

They can also be read as a whole for compatibility. The choices are:

For example, to align across empty lines and not across comments, either of these work.

AlignConsecutiveDeclarations: AcrossEmptyLines

AlignConsecutiveDeclarations: Enabled: true AcrossEmptyLines: true AcrossComments: false

#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
#define bar(y, z) (y + z)
int a = 1;
int somelongname = 2;
double c = 3;
int aaaa : 1;
int b : 12;
int ccc : 8;
int aaaa = 12;
float b = 23;
std::string ccc;

bbb >>= 2;
false:
a >>= 2;
bbb = 2;
a = 2;
bbb >>= 2;

AlignConsecutiveMacros (AlignConsecutiveStyle) clang-format 9

Style of aligning consecutive macro definitions.

Consecutive will result in formattings like:

#define SHORT_NAME 42 #define LONGER_NAME 0x007f #define EVEN_LONGER_NAME (2) #define foo(x) (x * x) #define bar(y, z) (y + z)

Nested configuration flags:

Alignment options.

They can also be read as a whole for compatibility. The choices are:

For example, to align across empty lines and not across comments, either of these work.

AlignConsecutiveMacros: AcrossEmptyLines

AlignConsecutiveMacros: Enabled: true AcrossEmptyLines: true AcrossComments: false

#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
#define bar(y, z) (y + z)
int a = 1;
int somelongname = 2;
double c = 3;
int aaaa : 1;
int b : 12;
int ccc : 8;
int aaaa = 12;
float b = 23;
std::string ccc;

bbb >>= 2;
false:
a >>= 2;
bbb = 2;
a = 2;
bbb >>= 2;

AlignConsecutiveShortCaseStatements (ShortCaseStatementsAlignmentStyle) clang-format 17

Style of aligning consecutive short case labels. Only applies if AllowShortCaseExpressionOnASingleLine orAllowShortCaseLabelsOnASingleLine is true.

Example of usage:

AlignConsecutiveShortCaseStatements: Enabled: true AcrossEmptyLines: true AcrossComments: true AlignCaseColons: false

Nested configuration flags:

Alignment options.

AlignConsecutiveTableGenBreakingDAGArgColons (AlignConsecutiveStyle) clang-format 19

Style of aligning consecutive TableGen DAGArg operator colons. If enabled, align the colon inside DAGArg which have line break inside. This works only when TableGenBreakInsideDAGArg is BreakElements or BreakAll and the DAGArg is not excepted by TableGenBreakingDAGArgOperators’s effect.

let dagarg = (ins a :$src1, aa :$src2, aaa:$src3 )

Nested configuration flags:

Alignment options.

They can also be read as a whole for compatibility. The choices are:

For example, to align across empty lines and not across comments, either of these work.

AlignConsecutiveTableGenBreakingDAGArgColons: AcrossEmptyLines

AlignConsecutiveTableGenBreakingDAGArgColons: Enabled: true AcrossEmptyLines: true AcrossComments: false

#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
#define bar(y, z) (y + z)
int a = 1;
int somelongname = 2;
double c = 3;
int aaaa : 1;
int b : 12;
int ccc : 8;
int aaaa = 12;
float b = 23;
std::string ccc;

bbb >>= 2;
false:
a >>= 2;
bbb = 2;
a = 2;
bbb >>= 2;

AlignConsecutiveTableGenCondOperatorColons (AlignConsecutiveStyle) clang-format 19

Style of aligning consecutive TableGen cond operator colons. Align the colons of cases inside !cond operators.

!cond(!eq(size, 1) : 1, !eq(size, 16): 1, true : 0)

Nested configuration flags:

Alignment options.

They can also be read as a whole for compatibility. The choices are:

For example, to align across empty lines and not across comments, either of these work.

AlignConsecutiveTableGenCondOperatorColons: AcrossEmptyLines

AlignConsecutiveTableGenCondOperatorColons: Enabled: true AcrossEmptyLines: true AcrossComments: false

#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
#define bar(y, z) (y + z)
int a = 1;
int somelongname = 2;
double c = 3;
int aaaa : 1;
int b : 12;
int ccc : 8;
int aaaa = 12;
float b = 23;
std::string ccc;

bbb >>= 2;
false:
a >>= 2;
bbb = 2;
a = 2;
bbb >>= 2;

AlignConsecutiveTableGenDefinitionColons (AlignConsecutiveStyle) clang-format 19

Style of aligning consecutive TableGen definition colons. This aligns the inheritance colons of consecutive definitions.

def Def : Parent {} def DefDef : Parent {} def DefDefDef : Parent {}

Nested configuration flags:

Alignment options.

They can also be read as a whole for compatibility. The choices are:

For example, to align across empty lines and not across comments, either of these work.

AlignConsecutiveTableGenDefinitionColons: AcrossEmptyLines

AlignConsecutiveTableGenDefinitionColons: Enabled: true AcrossEmptyLines: true AcrossComments: false

#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
#define bar(y, z) (y + z)
int a = 1;
int somelongname = 2;
double c = 3;
int aaaa : 1;
int b : 12;
int ccc : 8;
int aaaa = 12;
float b = 23;
std::string ccc;

bbb >>= 2;
false:
a >>= 2;
bbb = 2;
a = 2;
bbb >>= 2;

AlignEscapedNewlines (EscapedNewlineAlignmentStyle) clang-format 5

Options for aligning backslashes in escaped newlines.

Possible values:

#define A \
int aaaa; \
int b; \
int dddddddddd;

#define A \
int aaaa; \
int b; \
int dddddddddd;

#define A \
int aaaa; \
int b; \
int dddddddddd;

#define A \
int aaaa; \
int b; \
int dddddddddd;

AlignOperands (OperandAlignmentStyle) clang-format 3.5

If true, horizontally align operands of binary and ternary expressions.

Possible values:

When BreakBeforeBinaryOperators is set, the wrapped operator is aligned with the operand on the first line.
int aaa = bbbbbbbbbbbbbbb
+ ccccccccccccccc;

AllowAllArgumentsOnNextLine (Boolean) clang-format 9

If a function call or braced initializer list doesn’t fit on a line, allow putting all arguments onto the next line, even ifBinPackArguments is false.

true: callFunction( a, b, c, d);

false: callFunction(a, b, c, d);

AllowAllConstructorInitializersOnNextLine (Boolean) clang-format 9

This option is deprecated. See NextLine ofPackConstructorInitializers.

AllowAllParametersOfDeclarationOnNextLine (Boolean) clang-format 3.3

If the function declaration doesn’t fit on a line, allow putting all parameters of a function declaration onto the next line even if BinPackParameters is OnePerLine.

true: void myFunction( int a, int b, int c, int d, int e);

false: void myFunction(int a, int b, int c, int d, int e);

AllowBreakBeforeNoexceptSpecifier (BreakBeforeNoexceptSpecifierStyle) clang-format 18

Controls if there could be a line break before a noexcept specifier.

Possible values:

void bar(int arg1, double arg2) noexcept(
noexcept(baz(arg1)) &&
noexcept(baz(arg2)));

void bar(int arg1, double arg2)
noexcept(noexcept(baz(arg1)) &&
noexcept(baz(arg2)));

void bar(int arg1, double arg2)
noexcept(noexcept(baz(arg1)) &&
noexcept(baz(arg2)));

AllowShortBlocksOnASingleLine (ShortBlockStyle) clang-format 3.5

Dependent on the value, while (true) { continue; } can be put on a single line.

Possible values:

AllowShortCaseExpressionOnASingleLine (Boolean) clang-format 19

Whether to merge a short switch labeled rule into a single line.

true: false: switch (a) { vs. switch (a) { case 1 -> 1; case 1 -> default -> 0; 1; }; default -> 0; };

AllowShortCaseLabelsOnASingleLine (Boolean) clang-format 3.6

If true, short case labels will be contracted to a single line.

true: false: switch (a) { vs. switch (a) { case 1: x = 1; break; case 1: case 2: return; x = 1; } break; case 2: return; }

AllowShortCompoundRequirementOnASingleLine (Boolean) clang-format 18

Allow short compound requirement on a single line.

true: template concept c = requires(T x) { { x + 1 } -> std::same_as; };

false: template concept c = requires(T x) { { x + 1 } -> std::same_as; };

AllowShortEnumsOnASingleLine (Boolean) clang-format 11

Allow short enums on a single line.

true: enum { A, B } myEnum;

false: enum { A, B } myEnum;

AllowShortFunctionsOnASingleLine (ShortFunctionStyle) clang-format 3.5

Dependent on the value, int f() { return 0; } can be put on a single line.

Possible values:

AllowShortIfStatementsOnASingleLine (ShortIfStyle) clang-format 3.3

Dependent on the value, if (a) return; can be put on a single line.

Possible values:

AllowShortLambdasOnASingleLine (ShortLambdaStyle) clang-format 9

Dependent on the value, auto lambda []() { return 0; } can be put on a single line.

Possible values:

AllowShortLoopsOnASingleLine (Boolean) clang-format 3.7

If true, while (true) continue; can be put on a single line.

AllowShortNamespacesOnASingleLine (Boolean) clang-format 20

If true, namespace a { class b; } can be put on a single line.

AlwaysBreakAfterDefinitionReturnType (DefinitionReturnTypeBreakingStyle) clang-format 3.7

The function definition return type breaking style to use. This option is deprecated and is retained for backwards compatibility.

Possible values:

AlwaysBreakAfterReturnType (deprecated) clang-format 3.8

This option is renamed to BreakAfterReturnType.

AlwaysBreakBeforeMultilineStrings (Boolean) clang-format 3.4

If true, always break before multiline string literals.

This flag is mean to make cases where there are multiple multiline strings in a file look more consistent. Thus, it will only take effect if wrapping the string at that point leads to it being indentedContinuationIndentWidth spaces from the start of the line.

true: false: aaaa = vs. aaaa = "bbbb" "bbbb" "cccc"; "cccc";

AlwaysBreakTemplateDeclarations (deprecated) clang-format 3.4

This option is renamed to BreakTemplateDeclarations.

AttributeMacros (List of Strings) clang-format 12

A vector of strings that should be interpreted as attributes/qualifiers instead of identifiers. This can be useful for language extensions or static analyzer annotations.

For example:

x = (char *__capability)&y; int function(void) __unused; void only_writes_to_buffer(char *__output buffer);

In the .clang-format configuration file, this can be configured like:

AttributeMacros: [__capability, __output, __unused]

BinPackArguments (Boolean) clang-format 3.7

If false, a function call’s arguments will either be all on the same line or will have one line each.

true: void f() { f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa); }

false: void f() { f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa); }

BinPackLongBracedList (Boolean) clang-format 21

If BinPackLongBracedList is true it overridesBinPackArguments if there are 20 or more items in a braced initializer list.

BinPackLongBracedList: false vs. BinPackLongBracedList: true vector x{ vector x{1, 2, ..., 20, 21}; 1, 2, ..., 20, 21};

BinPackParameters (BinPackParametersStyle) clang-format 3.7

The bin pack parameters style to use.

Possible values:

BitFieldColonSpacing (BitFieldColonSpacingStyle) clang-format 12

The BitFieldColonSpacingStyle to use for bitfields.

Possible values:

BraceWrapping (BraceWrappingFlags) clang-format 3.8

Control of individual brace wrapping cases.

If BreakBeforeBraces is set to Custom, use this to specify how each individual brace case should be handled. Otherwise, this is ignored.

Example of usage:

BreakBeforeBraces: Custom BraceWrapping: AfterEnum: true AfterStruct: false SplitEmptyFunction: false

Nested configuration flags:

Precise control over the wrapping of braces.

Should be declared this way:

BreakBeforeBraces: Custom BraceWrapping: AfterClass: true

BracedInitializerIndentWidth (Integer) clang-format 17

The number of columns to use to indent the contents of braced init lists. If unset or negative, ContinuationIndentWidth is used.

AlignAfterOpenBracket: AlwaysBreak BracedInitializerIndentWidth: 2

void f() { SomeClass c{ "foo", "bar", "baz", }; auto s = SomeStruct{ .foo = "foo", .bar = "bar", .baz = "baz", }; SomeArrayT a[3] = { { foo, bar, }, { foo, bar, }, SomeArrayT{}, }; }

BreakAdjacentStringLiterals (Boolean) clang-format 18

Break between adjacent string literals.

true: return "Code" "\0\52\26\55\55\0" "x013" "\02\xBA"; false: return "Code" "\0\52\26\55\55\0" "x013" "\02\xBA";

BreakAfterAttributes (AttributeBreakingStyle) clang-format 16

Break after a group of C++11 attributes before variable or function (including constructor/destructor) declaration/definition names or before control statements, i.e. if, switch (including case anddefault labels), for, and while statements.

Possible values:

BreakAfterJavaFieldAnnotations (Boolean) clang-format 3.8

Break after each annotation on a field in Java files.

true: false: @Partial vs. @Partial @Mock DataLoad loader; @Mock DataLoad loader;

BreakAfterReturnType (ReturnTypeBreakingStyle) clang-format 19

The function declaration return type breaking style to use.

Possible values:

BreakArrays (Boolean) clang-format 16

If true, clang-format will always break after a Json array [otherwise it will scan until the closing ] to determine if it should add newlines between elements (prettier compatible).

Note

This is currently only for formatting JSON.

true: false: [ vs. [1, 2, 3, 4] 1, 2, 3, 4 ]

BreakBeforeBinaryOperators (BinaryOperatorStyle) clang-format 3.6

The way to wrap binary operators.

Possible values:

BreakBeforeBraces (BraceBreakingStyle) clang-format 3.7

The brace breaking style to use.

Possible values:

BreakBeforeConceptDeclarations (BreakBeforeConceptDeclarationsStyle) clang-format 12

The concept declaration style to use.

Possible values:

BreakBeforeInlineASMColon (BreakBeforeInlineASMColonStyle) clang-format 16

The inline ASM colon style to use.

Possible values:

BreakBeforeTemplateCloser (Boolean) clang-format 21

If true, break before a template closing bracket (>) when there is a line break after the matching opening bracket (<).

true: template <typename Foo, typename Bar>

template <typename Foo, typename Bar>

template < typename Foo, typename Bar

false: template <typename Foo, typename Bar>

template <typename Foo, typename Bar>

template < typename Foo, typename Bar>

BreakBeforeTernaryOperators (Boolean) clang-format 3.7

If true, ternary operators will be placed after line breaks.

true: veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ? firstValue : SecondValueVeryVeryVeryVeryLong;

false: veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ? firstValue : SecondValueVeryVeryVeryVeryLong;

BreakBinaryOperations (BreakBinaryOperationsStyle) clang-format 20

The break binary operations style to use.

Possible values:

BreakConstructorInitializers (BreakConstructorInitializersStyle) clang-format 5

The break constructor initializers style to use.

Possible values:

BreakFunctionDefinitionParameters (Boolean) clang-format 19

If true, clang-format will always break before function definition parameters.

true: void functionDefinition( int A, int B) {}

false: void functionDefinition(int A, int B) {}

BreakInheritanceList (BreakInheritanceListStyle) clang-format 7

The inheritance list style to use.

Possible values:

{};

{};

BreakStringLiterals (Boolean) clang-format 3.9

Allow breaking string literals when formatting.

In C, C++, and Objective-C:

true: const char* x = "veryVeryVeryVeryVeryVe" "ryVeryVeryVeryVeryVery" "VeryLongString";

false: const char* x = "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";

In C# and Java:

true: string x = "veryVeryVeryVeryVeryVe" + "ryVeryVeryVeryVeryVery" + "VeryLongString";

false: string x = "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";

C# interpolated strings are not broken.

In Verilog:

true: string x = {"veryVeryVeryVeryVeryVe", "ryVeryVeryVeryVeryVery", "VeryLongString"};

false: string x = "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";

BreakTemplateDeclarations (BreakTemplateDeclarationsStyle) clang-format 19

The template declaration breaking style to use.

Possible values:

}

}

}

}

ColumnLimit (Unsigned) clang-format 3.7

The column limit.

A column limit of 0 means that there is no column limit. In this case, clang-format will respect the input’s line breaking decisions within statements unless they contradict other rules.

CompactNamespaces (Boolean) clang-format 5

If true, consecutive namespace declarations will be on the same line. If false, each namespace is declared on a new line.

true: namespace Foo { namespace Bar { }}

false: namespace Foo { namespace Bar { } }

If it does not fit on a single line, the overflowing namespaces get wrapped:

namespace Foo { namespace Bar { namespace Extra { }}}

ConstructorInitializerAllOnOneLineOrOnePerLine (Boolean) clang-format 3.7

This option is deprecated. See CurrentLine ofPackConstructorInitializers.

ConstructorInitializerIndentWidth (Unsigned) clang-format 3.7

The number of characters to use for indentation of constructor initializer lists as well as inheritance lists.

ContinuationIndentWidth (Unsigned) clang-format 3.7

Indent width for line continuations.

ContinuationIndentWidth: 2

int i = // VeryVeryVeryVeryVeryLongComment longFunction( // Again a long comment arg);

Cpp11BracedListStyle (Boolean) clang-format 3.4

If true, format braced lists as best suited for C++11 braced lists.

Important differences:

Fundamentally, C++11 braced lists are formatted exactly like function calls would be formatted in their place. If the braced list follows a name (e.g. a type or variable name), clang-format formats as if the {} were the parentheses of a function call with that name. If there is no name, a zero-length name is assumed.

true: false: vector x{1, 2, 3, 4}; vs. vector x{ 1, 2, 3, 4 }; vector x{{}, {}, {}, {}}; vector x{ {}, {}, {}, {} }; f(MyMap[{composite, key}]); f(MyMap[{ composite, key }]); new int[3]{1, 2, 3}; new int[3]{ 1, 2, 3 };

DeriveLineEnding (Boolean) clang-format 10

This option is deprecated. See DeriveLF and DeriveCRLF ofLineEnding.

DerivePointerAlignment (Boolean) clang-format 3.7

If true, analyze the formatted file for the most common alignment of & and *. Pointer and reference alignment styles are going to be updated according to the preferences found in the file.PointerAlignment is then used only as fallback.

DisableFormat (Boolean) clang-format 3.7

Disables formatting completely.

EmptyLineAfterAccessModifier (EmptyLineAfterAccessModifierStyle) clang-format 13

Defines when to put an empty line after access modifiers.EmptyLineBeforeAccessModifier configuration handles the number of empty lines between two access modifiers.

Possible values:

EmptyLineBeforeAccessModifier (EmptyLineBeforeAccessModifierStyle) clang-format 12

Defines in which cases to put empty line before access modifiers.

Possible values:

EnumTrailingComma (EnumTrailingCommaStyle) clang-format 21

Insert a comma (if missing) or remove the comma at the end of an enumenumerator list.

Warning

Setting this option to any value other than Leave could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.

Possible values:

ExperimentalAutoDetectBinPacking (Boolean) clang-format 3.7

If true, clang-format detects whether function calls and definitions are formatted with one parameter per line.

Each call can be bin-packed, one-per-line or inconclusive. If it is inconclusive, e.g. completely on one line, but a decision needs to be made, clang-format analyzes whether there are other bin-packed cases in the input file and act accordingly.

Note

This is an experimental flag, that might go away or be renamed. Do not use this in config files, etc. Use at your own risk.

ForEachMacros (List of Strings) clang-format 3.7

A vector of macros that should be interpreted as foreach loops instead of as function calls.

These are expected to be macros of the form:

FOREACH(, ...)

In the .clang-format configuration file, this can be configured like:

ForEachMacros: [RANGES_FOR, FOREACH]

For example: BOOST_FOREACH.

IfMacros (List of Strings) clang-format 13

A vector of macros that should be interpreted as conditionals instead of as function calls.

These are expected to be macros of the form:

IF(...) else IF(...)

In the .clang-format configuration file, this can be configured like:

For example: KJ_IF_MAYBE

IncludeBlocks (IncludeBlocksStyle) clang-format 6

Dependent on the value, multiple #include blocks can be sorted as one and divided based on category.

Possible values:

#include "b.h" into #include "b.h"
#include <lib/main.h> #include "a.h"
#include "a.h" #include <lib/main.h>

#include "b.h" into #include "a.h"
#include "b.h"
#include <lib/main.h> #include <lib/main.h>
#include "a.h"

#include "b.h" into #include "a.h"
#include "b.h"
#include <lib/main.h>
#include "a.h" #include <lib/main.h>

IncludeCategories (List of IncludeCategories) clang-format 3.8

Regular expressions denoting the different #include categories used for ordering #includes.

POSIX extendedregular expressions are supported.

These regular expressions are matched against the filename of an include (including the <> or “”) in order. The value belonging to the first matching regular expression is assigned and #includes are sorted first according to increasing category number and then alphabetically within each category.

If none of the regular expressions match, INT_MAX is assigned as category. The main header for a source file automatically gets category 0. so that it is generally kept at the beginning of the #includes(https://llvm.org/docs/CodingStandards.html#include-style). However, you can also assign negative priorities if you have certain headers that always need to be first.

There is a third and optional field SortPriority which can used whileIncludeBlocks = IBS_Regroup to define the priority in which#includes should be ordered. The value of Priority defines the order of #include blocks and also allows the grouping of #includesof different priority. SortPriority is set to the value ofPriority as default if it is not assigned.

Each regular expression can be marked as case sensitive with the fieldCaseSensitive, per default it is not.

To configure this in the .clang-format file, use:

IncludeCategories:

IncludeIsMainRegex (String) clang-format 3.9

Specify a regular expression of suffixes that are allowed in the file-to-main-include mapping.

When guessing whether a #include is the “main” include (to assign category 0, see above), use this regex of allowed suffixes to the header stem. A partial match is done, so that: * "" means “arbitrary suffix” * "$" means “no suffix”

For example, if configured to "(_test)?$", then a header a.h would be seen as the “main” include in both a.cc and a_test.cc.

IncludeIsMainSourceRegex (String) clang-format 10

Specify a regular expression for files being formatted that are allowed to be considered “main” in the file-to-main-include mapping.

By default, clang-format considers files as “main” only when they end with: .c, .cc, .cpp, .c++, .cxx, .m or .mmextensions. For these files a guessing of “main” include takes place (to assign category 0, see above). This config option allows for additional suffixes and extensions for files to be considered as “main”.

For example, if this option is configured to (Impl\.hpp)$, then a file ClassImpl.hpp is considered “main” (in addition toClass.c, Class.cc, Class.cpp and so on) and “main include file” logic will be executed (with IncludeIsMainRegex setting also being respected in later phase). Without this option set,ClassImpl.hpp would not have the main include file put on top before any other include.

IndentAccessModifiers (Boolean) clang-format 13

Specify whether access modifiers should have their own indentation level.

When false, access modifiers are indented (or outdented) relative to the record members, respecting the AccessModifierOffset. Record members are indented one level below the record. When true, access modifiers get their own indentation level. As a consequence, record members are always indented 2 levels below the record, regardless of the access modifier presence. Value of theAccessModifierOffset is ignored.

false: true: class C { vs. class C { class D { class D { void bar(); void bar(); protected: protected: D(); D(); }; }; public: public: C(); C(); }; }; void foo() { void foo() { return 1; return 1; } }

IndentCaseBlocks (Boolean) clang-format 11

Indent case label blocks one level from the case label.

When false, the block following the case label uses the same indentation level as for the case label, treating the case label the same as an if-statement. When true, the block gets indented as a scope block.

false: true: switch (fool) { vs. switch (fool) { case 1: { case 1: bar(); { } break; bar(); default: { } plop(); break; } default: } { plop(); } }

IndentCaseLabels (Boolean) clang-format 3.3

Indent case labels one level from the switch statement.

When false, use the same indentation level as for the switch statement. Switch statement body is always indented one level more than case labels (except the first block following the case label, which itself indents the code - unless IndentCaseBlocks is enabled).

false: true: switch (fool) { vs. switch (fool) { case 1: case 1: bar(); bar(); break; break; default: default: plop(); plop(); } }

IndentExportBlock (Boolean) clang-format 20

If true, clang-format will indent the body of an export { ... }block. This doesn’t affect the formatting of anything else related to exported declarations.

true: false: export { vs. export { void foo(); void foo(); void bar(); void bar(); } }

IndentExternBlock (IndentExternBlockStyle) clang-format 11

IndentExternBlockStyle is the type of indenting of extern blocks.

Possible values:

IndentGotoLabels (Boolean) clang-format 10

Indent goto labels.

When false, goto labels are flushed left.

true: false: int f() { vs. int f() { if (foo()) { if (foo()) { label1: label1: bar(); bar(); } } label2: label2: return 1; return 1; } }

IndentPPDirectives (PPDirectiveIndentStyle) clang-format 6

The preprocessor directive indenting style to use.

Possible values:

#if FOO
#if BAR
#include
#endif
#endif

#if FOO

if BAR

include

endif

#endif

#if FOO
#if BAR
#include
#endif
#endif

IndentRequiresClause (Boolean) clang-format 15

Indent the requires clause in a template. This only applies whenRequiresClausePosition is OwnLine, OwnLineWithBrace, or WithFollowing.

In clang-format 12, 13 and 14 it was named IndentRequires.

true: template requires Iterator void sort(It begin, It end) { //.... }

false: template requires Iterator void sort(It begin, It end) { //.... }

IndentWidth (Unsigned) clang-format 3.7

The number of columns to use for indentation.

IndentWidth: 3

void f() { someFunction(); if (true, false) { f(); } }

IndentWrappedFunctionNames (Boolean) clang-format 3.7

Indent if a function definition or declaration is wrapped after the type.

true: LoooooooooooooooooooooooooooooooooooooooongReturnType LoooooooooooooooooooooooooooooooongFunctionDeclaration();

false: LoooooooooooooooooooooooooooooooooooooooongReturnType LoooooooooooooooooooooooooooooooongFunctionDeclaration();

InsertBraces (Boolean) clang-format 15

Insert braces after control statements (if, else, for, do, and while) in C++ unless the control statements are inside macro definitions or the braces would enclose preprocessor directives.

Warning

Setting this option to true could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.

false: true:

if (isa(D)) vs. if (isa(D)) { handleFunctionDecl(D); handleFunctionDecl(D); else if (isa(D)) } else if (isa(D)) { handleVarDecl(D); handleVarDecl(D); else } else { return; return; }

while (i--) vs. while (i--) { for (auto *A : D.attrs()) for (auto *A : D.attrs()) { handleAttr(A); handleAttr(A); } }

do vs. do { --i; --i; while (i); } while (i);

InsertNewlineAtEOF (Boolean) clang-format 16

Insert a newline at end of file if missing.

InsertTrailingCommas (TrailingCommaStyle) clang-format 11

If set to TCS_Wrapped will insert trailing commas in container literals (arrays and objects) that wrap across multiple lines. It is currently only available for JavaScript and disabled by default TCS_None.InsertTrailingCommas cannot be used together with BinPackArgumentsas inserting the comma disables bin-packing.

TSC_Wrapped: const someArray = [ aaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa, // ^ inserted ]

Possible values:

IntegerLiteralSeparator (IntegerLiteralSeparatorStyle) clang-format 16

Format integer literal separators (' for C++ and _ for C#, Java, and JavaScript).

Nested configuration flags:

Separator format of integer literals of different bases.

If negative, remove separators. If 0, leave the literal as is. If positive, insert separators between digits starting from the rightmost digit.

For example, the config below will leave separators in binary literals alone, insert separators in decimal literals to separate the digits into groups of 3, and remove separators in hexadecimal literals.

IntegerLiteralSeparator: Binary: 0 Decimal: 3 Hex: -1

You can also specify a minimum number of digits (BinaryMinDigits,DecimalMinDigits, and HexMinDigits) the integer literal must have in order for the separators to be inserted.

JavaImportGroups (List of Strings) clang-format 8

A vector of prefixes ordered by the desired groups for Java imports.

One group’s prefix can be a subset of another - the longest prefix is always matched. Within a group, the imports are ordered lexicographically. Static imports are grouped separately and follow the same group rules. By default, static imports are placed before non-static imports, but this behavior is changed by another option,SortJavaStaticImport.

In the .clang-format configuration file, this can be configured like in the following yaml example. This will result in imports being formatted as in the Java example below.

JavaImportGroups: [com.example, com, org]

import static com.example.function1;

import static com.test.function2;

import static org.example.function3;

import com.example.ClassA; import com.example.Test; import com.example.a.ClassB;

import com.test.ClassC;

import org.example.ClassD;

JavaScriptQuotes (JavaScriptQuoteStyle) clang-format 3.9

The JavaScriptQuoteStyle to use for JavaScript strings.

Possible values:

JavaScriptWrapImports (Boolean) clang-format 3.9

Whether to wrap JavaScript import/export statements.

true: import { VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, } from "some/module.js"

false: import {VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying,} from "some/module.js"

KeepEmptyLines (KeepEmptyLinesStyle) clang-format 19

Which empty lines are kept. See MaxEmptyLinesToKeep for how many consecutive empty lines are kept.

Nested configuration flags:

Options regarding which empty lines are kept.

For example, the config below will remove empty lines at start of the file, end of the file, and start of blocks.

KeepEmptyLines: AtEndOfFile: false AtStartOfBlock: false AtStartOfFile: false

KeepEmptyLinesAtEOF (Boolean) clang-format 17

This option is deprecated. See AtEndOfFile of KeepEmptyLines.

KeepEmptyLinesAtTheStartOfBlocks (Boolean) clang-format 3.7

This option is deprecated. See AtStartOfBlock ofKeepEmptyLines.

KeepFormFeed (Boolean) clang-format 20

Keep the form feed character if it’s immediately preceded and followed by a newline. Multiple form feeds and newlines within a whitespace range are replaced with a single newline and form feed followed by the remaining newlines.

LambdaBodyIndentation (LambdaBodyIndentationKind) clang-format 13

The indentation style of lambda bodies. Signature (the default) causes the lambda body to be indented one additional level relative to the indentation level of the signature. OuterScope forces the lambda body to be indented one additional level relative to the parent scope containing the lambda signature.

Possible values:

Language (LanguageKind) clang-format 3.5

The language that this format style targets.

Note

You can specify the language (C, Cpp, or ObjC) for .hfiles by adding a // clang-format Language: line before the first non-comment (and non-empty) line, e.g. // clang-format Language: Cpp.

Possible values:

LineEnding (LineEndingStyle) clang-format 16

Line ending style (\n or \r\n) to use.

Possible values:

MacroBlockBegin (String) clang-format 3.7

A regular expression matching macros that start a block.

With:

MacroBlockBegin: "^NS_MAP_BEGIN|
NS_TABLE_HEAD$" MacroBlockEnd: "^
NS_MAP_END|
NS_TABLE_.*_END$"

NS_MAP_BEGIN foo(); NS_MAP_END

NS_TABLE_HEAD bar(); NS_TABLE_FOO_END

Without:

NS_MAP_BEGIN foo(); NS_MAP_END

NS_TABLE_HEAD bar(); NS_TABLE_FOO_END

MacroBlockEnd (String) clang-format 3.7

A regular expression matching macros that end a block.

Macros (List of Strings) clang-format 17

A list of macros of the form <definition>=<expansion> .

Code will be parsed with macros expanded, in order to determine how to interpret and format the macro arguments.

For example, the code:

will usually be interpreted as a call to a function A, and the multiplication expression will be formatted as a * b.

If we specify the macro definition:

the code will now be parsed as a declaration of the variable b of type a*, and formatted as a* b (depending on pointer-binding rules).

Features and restrictions:

A; -> x; A(); -> y; A(z); -> z; A(a, b); // will not be expanded.

MainIncludeChar (MainIncludeCharDiscriminator) clang-format 19

When guessing whether a #include is the “main” include, only the include directives that use the specified character are considered.

Possible values:

MaxEmptyLinesToKeep (Unsigned) clang-format 3.7

The maximum number of consecutive empty lines to keep.

MaxEmptyLinesToKeep: 1 vs. MaxEmptyLinesToKeep: 0 int f() { int f() { int = 1; int i = 1; i = foo(); i = foo(); return i; } return i; }

NamespaceIndentation (NamespaceIndentationKind) clang-format 3.7

The indentation used for namespaces.

Possible values:

NamespaceMacros (List of Strings) clang-format 9

A vector of macros which are used to open namespace blocks.

These are expected to be macros of the form:

NAMESPACE(, ...) { }

For example: TESTSUITE

ObjCBinPackProtocolList (BinPackStyle) clang-format 7

Controls bin-packing Objective-C protocol conformance list items into as few lines as possible when they go over ColumnLimit.

If Auto (the default), delegates to the value inBinPackParameters. If that is BinPack, bin-packs Objective-C protocol conformance list items into as few lines as possible whenever they go over ColumnLimit.

If Always, always bin-packs Objective-C protocol conformance list items into as few lines as possible whenever they go overColumnLimit.

If Never, lays out Objective-C protocol conformance list items onto individual lines whenever they go over ColumnLimit.

Always (or Auto, if BinPackParameters==BinPack): @interface ccccccccccccc () < ccccccccccccc, ccccccccccccc, ccccccccccccc, ccccccccccccc> { }

Never (or Auto, if BinPackParameters!=BinPack): @interface ddddddddddddd () < ddddddddddddd, ddddddddddddd, ddddddddddddd, ddddddddddddd> { }

Possible values:

ObjCBlockIndentWidth (Unsigned) clang-format 3.7

The number of characters to use for indentation of ObjC blocks.

ObjCBlockIndentWidth: 4

[operation setCompletionBlock:^{ [self onOperationDone]; }];

ObjCBreakBeforeNestedBlockParam (Boolean) clang-format 11

Break parameters list into lines when there is nested block parameters in a function call.

false:

}

ObjCPropertyAttributeOrder (List of Strings) clang-format 18

The order in which ObjC property attributes should appear.

Attributes in code will be sorted in the order specified. Any attributes encountered that are not mentioned in this array will be sorted last, in stable order. Comments between attributes will leave the attributes untouched.

Warning

Using this option could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.

ObjCPropertyAttributeOrder: [ class, direct, atomic, nonatomic, assign, retain, strong, copy, weak, unsafe_unretained, readonly, readwrite, getter, setter, nullable, nonnull, null_resettable, null_unspecified ]

ObjCSpaceAfterProperty (Boolean) clang-format 3.7

Add a space after @property in Objective-C, i.e. use@property (readonly) instead of @property(readonly).

ObjCSpaceBeforeProtocolList (Boolean) clang-format 3.7

Add a space in front of an Objective-C protocol list, i.e. useFoo <Protocol> instead of Foo<Protocol>.

OneLineFormatOffRegex (String) clang-format 21

A regular expression that describes markers for turning formatting off for one line. If it matches a comment that is the only token of a line, clang-format skips the comment and the next line. Otherwise, clang-format skips lines containing a matched token.

// OneLineFormatOffRegex: ^(// NOLINT|logger$) // results in the output below: int a; int b ; // NOLINT int c; // NOLINTNEXTLINE int d ; int e; s = "// NOLINT"; logger() ; logger2(); my_logger();

PPIndentWidth (Integer) clang-format 13

The number of columns to use for indentation of preprocessor statements. When set to -1 (default) IndentWidth is used also for preprocessor statements.

PPIndentWidth: 1

#ifdef linux

define FOO

#else

define BAR

#endif

PackConstructorInitializers (PackConstructorInitializersStyle) clang-format 14

The pack constructor initializers style to use.

Possible values:

PenaltyBreakAssignment (Unsigned) clang-format 5

The penalty for breaking around an assignment operator.

PenaltyBreakBeforeFirstCallParameter (Unsigned) clang-format 3.7

The penalty for breaking a function call after call(.

PenaltyBreakBeforeMemberAccess (Unsigned) clang-format 20

The penalty for breaking before a member access operator (., ->).

PenaltyBreakFirstLessLess (Unsigned) clang-format 3.7

The penalty for breaking before the first <<.

PenaltyBreakOpenParenthesis (Unsigned) clang-format 14

The penalty for breaking after (.

PenaltyBreakScopeResolution (Unsigned) clang-format 18

The penalty for breaking after ::.

PenaltyBreakString (Unsigned) clang-format 3.7

The penalty for each line break introduced inside a string literal.

PenaltyBreakTemplateDeclaration (Unsigned) clang-format 7

The penalty for breaking after template declaration.

PenaltyExcessCharacter (Unsigned) clang-format 3.7

The penalty for each character outside of the column limit.

PenaltyIndentedWhitespace (Unsigned) clang-format 12

Penalty for each character of whitespace indentation (counted relative to leading non-whitespace column).

PenaltyReturnTypeOnItsOwnLine (Unsigned) clang-format 3.7

Penalty for putting the return type of a function onto its own line.

PointerAlignment (PointerAlignmentStyle) clang-format 3.7

Pointer and reference alignment style.

Possible values:

QualifierAlignment (QualifierAlignmentStyle) clang-format 14

Different ways to arrange specifiers and qualifiers (e.g. const/volatile).

Warning

Setting QualifierAlignment to something other than Leave, COULD lead to incorrect code formatting due to incorrect decisions made due to clang-formats lack of complete semantic information. As such extra care should be taken to review code changes made by the use of this option.

Possible values:

QualifierOrder (List of Strings) clang-format 14

The order in which the qualifiers appear. The order is an array that can contain any of the following:

Note

It must contain type.

Items to the left of type will be placed to the left of the type and aligned in the order supplied. Items to the right of type will be placed to the right of the type and aligned in the order supplied.

QualifierOrder: [inline, static, type, const, volatile]

RawStringFormats (List of RawStringFormats) clang-format 6

Defines hints for detecting supported languages code blocks in raw strings.

A raw string with a matching delimiter or a matching enclosing function name will be reformatted assuming the specified language based on the style for that language defined in the .clang-format file. If no style has been defined in the .clang-format file for the specific language, a predefined style given by BasedOnStyle is used. If BasedOnStyle is not found, the formatting is based on LLVM style. A matching delimiter takes precedence over a matching enclosing function name for determining the language of the raw string contents.

If a canonical delimiter is specified, occurrences of other delimiters for the same language will be updated to the canonical if possible.

There should be at most one specification per language and each delimiter and enclosing function should not occur in multiple specifications.

To configure this in the .clang-format file, use:

RawStringFormats:

ReferenceAlignment (ReferenceAlignmentStyle) clang-format 13

Reference alignment style (overrides PointerAlignment for references).

Possible values:

RemoveBracesLLVM (Boolean) clang-format 14

Remove optional braces of control statements (if, else, for, and while) in C++ according to the LLVM coding style.

Warning

This option will be renamed and expanded to support other styles.

Warning

Setting this option to true could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.

false: true:

if (isa(D)) { vs. if (isa(D)) handleFunctionDecl(D); handleFunctionDecl(D); } else if (isa(D)) { else if (isa(D)) handleVarDecl(D); handleVarDecl(D); }

if (isa(D)) { vs. if (isa(D)) { for (auto *A : D.attrs()) { for (auto *A : D.attrs()) if (shouldProcessAttr(A)) { if (shouldProcessAttr(A)) handleAttr(A); handleAttr(A); } } } }

if (isa(D)) { vs. if (isa(D)) for (auto *A : D.attrs()) { for (auto *A : D.attrs()) handleAttr(A); handleAttr(A); } }

if (auto *D = (T)(D)) { vs. if (auto *D = (T)(D)) { if (shouldProcess(D)) { if (shouldProcess(D)) handleVarDecl(D); handleVarDecl(D); } else { else markAsIgnored(D); markAsIgnored(D); } } }

if (a) { vs. if (a) b(); b(); } else { else if (c) if (c) { d(); d(); else } else { e(); e(); } }

RemoveEmptyLinesInUnwrappedLines (Boolean) clang-format 20

Remove empty lines within unwrapped lines.

false: true:

int c vs. int c = a + b;

= a + b;

enum : unsigned vs. enum : unsigned { AA = 0, { BB AA = 0, } myEnum; BB } myEnum;

while ( vs. while (true) { } true) { }

RemoveParentheses (RemoveParenthesesStyle) clang-format 17

Remove redundant parentheses.

Warning

Setting this option to any value other than Leave could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.

Possible values:

RemoveSemicolon (Boolean) clang-format 16

Remove semicolons after the closing braces of functions and constructors/destructors.

Warning

Setting this option to true could lead to incorrect code formatting due to clang-format’s lack of complete semantic information. As such, extra care should be taken to review code changes made by this option.

false: true:

int max(int a, int b) { int max(int a, int b) { return a > b ? a : b; return a > b ? a : b; }; }

RequiresClausePosition (RequiresClausePositionStyle) clang-format 15

The position of the requires clause.

Possible values:

RequiresExpressionIndentation (RequiresExpressionIndentationKind) clang-format 16

The indentation used for requires expression bodies.

Possible values:

SeparateDefinitionBlocks (SeparateDefinitionStyle) clang-format 14

Specifies the use of empty lines to separate definition blocks, including classes, structs, enums, and functions.

Never v.s. Always #include #include struct Foo { int a, b, c; struct Foo { }; int a, b, c; namespace Ns { }; class Bar { public: namespace Ns { struct Foobar { class Bar { int a; public: int b; struct Foobar { }; int a; private: int b; int t; }; int method1() { // ... private: } int t; enum List { ITEM1, int method1() { ITEM2 // ... }; } template int method2(T x) { enum List { // ... ITEM1, } ITEM2 int i, j, k; }; int method3(int par) { // ... template } int method2(T x) { }; // ... class C {}; } } int i, j, k;

                              int method3(int par) {
                                // ...
                              }
                            };

                            class C {};
                            }

Possible values:

ShortNamespaceLines (Unsigned) clang-format 13

The maximal number of unwrapped lines that a short namespace spans. Defaults to 1.

This determines the maximum length of short namespaces by counting unwrapped lines (i.e. containing neither opening nor closing namespace brace) and makes FixNamespaceComments omit adding end comments for those.

ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0 namespace a { namespace a { int foo; int foo; } } // namespace a

ShortNamespaceLines: 1 vs. ShortNamespaceLines: 0 namespace b { namespace b { int foo; int foo; int bar; int bar; } // namespace b } // namespace b

SkipMacroDefinitionBody (Boolean) clang-format 18

Do not format macro definition body.

SortIncludes (SortIncludesOptions) clang-format 3.8

Controls if and how clang-format will sort #includes.

Possible values:

#include "B/A.h"
#include "A/B.h"
#include "a/b.h"
#include "A/b.h"
#include "B/a.h"

#include "A/B.h"
#include "A/b.h"
#include "B/A.h"
#include "B/a.h"
#include "a/b.h"

#include "A/B.h"
#include "A/b.h"
#include "a/b.h"
#include "B/A.h"
#include "B/a.h"

SortJavaStaticImport (SortJavaStaticImportOptions) clang-format 12

When sorting Java imports, by default static imports are placed before non-static imports. If JavaStaticImportAfterImport is After, static imports are placed after non-static imports.

Possible values:

SortUsingDeclarations (SortUsingDeclarationsOptions) clang-format 5

Controls if and how clang-format will sort using declarations.

Possible values:

SpaceAfterCStyleCast (Boolean) clang-format 3.5

If true, a space is inserted after C style casts.

true: false: (int) i; vs. (int)i;

SpaceAfterLogicalNot (Boolean) clang-format 9

If true, a space is inserted after the logical not operator (!).

true: false: ! someExpression(); vs. !someExpression();

SpaceAfterTemplateKeyword (Boolean) clang-format 4

If true, a space will be inserted after the template keyword.

true: false: template void foo(); vs. template void foo();

SpaceAroundPointerQualifiers (SpaceAroundPointerQualifiersStyle) clang-format 12

Defines in which cases to put a space before or after pointer qualifiers

Possible values:

SpaceBeforeAssignmentOperators (Boolean) clang-format 3.7

If false, spaces will be removed before assignment operators.

true: false: int a = 5; vs. int a= 5; a += 42; a+= 42;

SpaceBeforeCaseColon (Boolean) clang-format 12

If false, spaces will be removed before case colon.

true: false switch (x) { vs. switch (x) { case 1 : break; case 1: break; } }

SpaceBeforeCpp11BracedList (Boolean) clang-format 7

If true, a space will be inserted before a C++11 braced list used to initialize an object (after the preceding identifier or type).

true: false: Foo foo { bar }; vs. Foo foo{ bar }; Foo {}; Foo{}; vector { 1, 2, 3 }; vector{ 1, 2, 3 }; new int[3] { 1, 2, 3 }; new int[3]{ 1, 2, 3 };

SpaceBeforeCtorInitializerColon (Boolean) clang-format 7

If false, spaces will be removed before constructor initializer colon.

true: false: Foo::Foo() : a(a) {} Foo::Foo(): a(a) {}

SpaceBeforeInheritanceColon (Boolean) clang-format 7

If false, spaces will be removed before inheritance colon.

true: false: class Foo : Bar {} vs. class Foo: Bar {}

SpaceBeforeJsonColon (Boolean) clang-format 17

If true, a space will be added before a JSON colon. For other languages, e.g. JavaScript, use SpacesInContainerLiterals instead.

true: false: { { "key" : "value" vs. "key": "value" } }

SpaceBeforeParens (SpaceBeforeParensStyle) clang-format 3.5

Defines in which cases to put a space before opening parentheses.

Possible values:

SpaceBeforeParensOptions (SpaceBeforeParensCustom) clang-format 14

Control of individual space before parentheses.

If SpaceBeforeParens is set to Custom, use this to specify how each individual space before parentheses case should be handled. Otherwise, this is ignored.

Example of usage:

SpaceBeforeParens: Custom SpaceBeforeParensOptions: AfterControlStatements: true AfterFunctionDefinitionName: true

Nested configuration flags:

Precise control over the spacing before parentheses.

Should be declared this way:

SpaceBeforeParens: Custom SpaceBeforeParensOptions: AfterControlStatements: true AfterFunctionDefinitionName: true

SpaceBeforeRangeBasedForLoopColon (Boolean) clang-format 7

If false, spaces will be removed before range-based for loop colon.

true: false: for (auto v : values) {} vs. for(auto v: values) {}

SpaceBeforeSquareBrackets (Boolean) clang-format 10

If true, spaces will be before [. Lambdas will not be affected. Only the first [ will get a space added.

true: false: int a [5]; vs. int a[5]; int a [5][5]; vs. int a[5][5];

SpaceInEmptyBlock (Boolean) clang-format 10

If true, spaces will be inserted into {}.

true: false: void f() { } vs. void f() {} while (true) { } while (true) {}

SpaceInEmptyParentheses (Boolean) clang-format 3.7

If true, spaces may be inserted into (). This option is deprecated. See InEmptyParentheses ofSpacesInParensOptions.

SpacesInAngles (SpacesInAnglesStyle) clang-format 3.4

The SpacesInAnglesStyle to use for template argument lists.

Possible values:

SpacesInCStyleCastParentheses (Boolean) clang-format 3.7

If true, spaces may be inserted into C style casts. This option is deprecated. See InCStyleCasts ofSpacesInParensOptions.

SpacesInConditionalStatement (Boolean) clang-format 10

If true, spaces will be inserted around if/for/switch/while conditions. This option is deprecated. See InConditionalStatements ofSpacesInParensOptions.

SpacesInContainerLiterals (Boolean) clang-format 3.7

If true, spaces are inserted inside container literals (e.g. ObjC and Javascript array and dict literals). For JSON, useSpaceBeforeJsonColon instead.

true: false: var arr = [ 1, 2, 3 ]; vs. var arr = [1, 2, 3]; f({a : 1, b : 2, c : 3}); f({a: 1, b: 2, c: 3});

SpacesInParens (SpacesInParensStyle) clang-format 17

Defines in which cases spaces will be inserted after ( and before).

Possible values:

SpacesInParensOptions (SpacesInParensCustom) clang-format 17

Control of individual spaces in parentheses.

If SpacesInParens is set to Custom, use this to specify how each individual space in parentheses case should be handled. Otherwise, this is ignored.

Example of usage:

SpacesInParens: Custom SpacesInParensOptions: ExceptDoubleParentheses: false InConditionalStatements: true InEmptyParentheses: true

Nested configuration flags:

Precise control over the spacing in parentheses.

Should be declared this way:

SpacesInParens: Custom SpacesInParensOptions: ExceptDoubleParentheses: false InConditionalStatements: true Other: true

SpacesInParentheses (Boolean) clang-format 3.7

If true, spaces will be inserted after ( and before ). This option is deprecated. The previous behavior is preserved by usingSpacesInParens with Custom and by setting allSpacesInParensOptions to true except for InCStyleCasts andInEmptyParentheses.

SpacesInSquareBrackets (Boolean) clang-format 3.7

If true, spaces will be inserted after [ and before ]. Lambdas without arguments or unspecified size array declarations will not be affected.

true: false: int a[ 5 ]; vs. int a[5]; std::unique_ptr<int[]> foo() {} // Won't be affected

Standard (LanguageStandard) clang-format 3.7

Parse and format C++ constructs compatible with this standard.

c++03: latest: vector<set > x; vs. vector<set> x;

Possible values:

StatementAttributeLikeMacros (List of Strings) clang-format 12

Macros which are ignored in front of a statement, as if they were an attribute. So that they are not parsed as identifier, for example for Qts emit.

AlignConsecutiveDeclarations: true StatementAttributeLikeMacros: [] unsigned char data = 'x'; emit signal(data); // This is parsed as variable declaration.

AlignConsecutiveDeclarations: true StatementAttributeLikeMacros: [emit] unsigned char data = 'x'; emit signal(data); // Now it's fine again.

StatementMacros (List of Strings) clang-format 8

A vector of macros that should be interpreted as complete statements.

Typical macros are expressions and require a semicolon to be added. Sometimes this is not the case, and this allows to make clang-format aware of such cases.

For example: Q_UNUSED

TabWidth (Unsigned) clang-format 3.7

The number of columns used for tab stops.

TableGenBreakInsideDAGArg (DAGArgStyle) clang-format 19

The styles of the line break inside the DAGArg in TableGen.

Possible values:

TableGenBreakingDAGArgOperators (List of Strings) clang-format 19

Works only when TableGenBreakInsideDAGArg is not DontBreak. The string list needs to consist of identifiers in TableGen. If any identifier is specified, this limits the line breaks by TableGenBreakInsideDAGArg option only on DAGArg values beginning with the specified identifiers.

For example the configuration,

TableGenBreakInsideDAGArg: BreakAll TableGenBreakingDAGArgOperators: [ins, outs]

makes the line break only occurs inside DAGArgs beginning with the specified identifiers ins and outs.

let DAGArgIns = (ins i32:$src1, i32:$src2 ); let DAGArgOtherID = (other i32:$other1, i32:$other2); let DAGArgBang = (!cast("Some") i32:$src1, i32:$src2)

TemplateNames (List of Strings) clang-format 20

A vector of non-keyword identifiers that should be interpreted as template names.

A < after a template name is annotated as a template opener instead of a binary operator.

TypeNames (List of Strings) clang-format 17

A vector of non-keyword identifiers that should be interpreted as type names.

A *, &, or && between a type name and another non-keyword identifier is annotated as a pointer or reference token instead of a binary operator.

TypenameMacros (List of Strings) clang-format 9

A vector of macros that should be interpreted as type declarations instead of as function calls.

These are expected to be macros of the form:

In the .clang-format configuration file, this can be configured like:

TypenameMacros: [STACK_OF, LIST]

For example: OpenSSL STACK_OF, BSD LIST_ENTRY.

UseCRLF (Boolean) clang-format 10

This option is deprecated. See LF and CRLF of LineEnding.

UseTab (UseTabStyle) clang-format 3.7

The way to use tab characters in the resulting file.

Possible values:

VariableTemplates (List of Strings) clang-format 20

A vector of non-keyword identifiers that should be interpreted as variable template names.

A ) after a variable template instantiation is not annotated as the closing parenthesis of C-style cast operator.

VerilogBreakBetweenInstancePorts (Boolean) clang-format 17

For Verilog, put each port on its own line in module instantiations.

true: ffnand ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));

false: ffnand ff1(.q(), .qbar(out1), .clear(in1), .preset(in2));

WhitespaceSensitiveMacros (List of Strings) clang-format 11

A vector of macros which are whitespace-sensitive and should not be touched.

These are expected to be macros of the form:

In the .clang-format configuration file, this can be configured like:

WhitespaceSensitiveMacros: [STRINGIZE, PP_STRINGIZE]

For example: BOOST_PP_STRINGIZE

WrapNamespaceBodyWithEmptyLines (WrapNamespaceBodyWithEmptyLinesStyle) clang-format 20

Wrap namespace body with empty lines.

Possible values:

Adding additional style options

Each additional style option adds costs to the clang-format project. Some of these costs affect the clang-format development itself, as we need to make sure that any given combination of options work and that new features don’t break any of the existing options in any way. There are also costs for end users as options become less discoverable and people have to think about and make a decision on options they don’t really care about.

The goal of the clang-format project is more on the side of supporting a limited set of styles really well as opposed to supporting every single style used by a codebase somewhere in the wild. Of course, we do want to support all major projects and thus have established the following bar for adding style options. Each new style option must:

Examples

A style similar to the Linux Kernel style:

BasedOnStyle: LLVM IndentWidth: 8 UseTab: Always BreakBeforeBraces: Linux AllowShortIfStatementsOnASingleLine: false IndentCaseLabels: false

The result is (imagine that tabs are used for indentation here):

void test() { switch (x) { case 0: case 1: do_something(); break; case 2: do_something_else(); break; default: break; } if (condition) do_something_completely_different();

    if (x == y) {
            q();
    } else if (x > y) {
            w();
    } else {
            r();
    }

}

A style similar to the default Visual Studio formatting style:

UseTab: Never IndentWidth: 4 BreakBeforeBraces: Allman AllowShortIfStatementsOnASingleLine: false IndentCaseLabels: false ColumnLimit: 0

The result is:

void test() { switch (suffix) { case 0: case 1: do_something(); break; case 2: do_something_else(); break; default: break; } if (condition) do_something_completely_different();

if (x == y)
{
    q();
}
else if (x > y)
{
    w();
}
else
{
    r();
}

}