Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:49:58 +08:00
commit 5007abf04b
89 changed files with 44129 additions and 0 deletions

View File

@@ -0,0 +1,500 @@
# Alignment Options
[← Back to Index](index.md) | [CLI Usage](cli-usage.md) | [Next: Breaking →](02-breaking.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Options for aligning code elements to improve readability and consistency.
## Overview
Alignment options control how clang-format aligns various code elements vertically. These options help create visually organized code where related elements line up in columns.
## Quick Examples
**Aligned Assignments:**
```cpp
int a = 1;
int somelongname = 2;
double c = 3;
```
**Aligned Declarations:**
```cpp
int aaaa = 12;
float b = 23;
std::string ccc = 23;
```
**Aligned Macros:**
```cpp
#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
```
## Core Alignment Options
### AlignAfterOpenBracket
Controls alignment of parameters after an opening bracket.
**Type:** `BracketAlignmentStyle` **Values:**
- `Align` - Align parameters on the open bracket
- `DontAlign` - Don't align, use ContinuationIndentWidth
- `AlwaysBreak` - Always break after bracket
- `BlockIndent` - Always break and increase indent
**Examples:**
`Align`:
```cpp
someLongFunction(argument1,
argument2);
```
`DontAlign`:
```cpp
someLongFunction(argument1,
argument2);
```
`AlwaysBreak`:
```cpp
someLongFunction(
argument1, argument2);
```
`BlockIndent`:
```cpp
someLongFunction(
argument1,
argument2
);
```
### AlignArrayOfStructures
Align array of structures horizontally.
**Type:** `ArrayInitializerAlignmentStyle` **Values:**
- `None` - Don't align array initializers
- `Left` - Align and left-justify initializers
- `Right` - Align and right-justify initializers
**Examples:**
`None`:
```cpp
struct test demo[] = {
{56, 23, "hello"},
{-1, 93463, "world"},
{7, 5, "!"}
};
```
`Left`:
```cpp
struct test demo[] = {
{56, 23, "hello"},
{-1, 93463, "world"},
{7, 5, "!" }
};
```
`Right`:
```cpp
struct test demo[] = {
{ 56, 23, "hello"},
{ -1, 93463, "world"},
{ 7, 5, "!" }
};
```
### AlignConsecutiveAssignments
Align consecutive assignment statements.
**Type:** `AlignConsecutiveStyle` **Sub-options:**
- `Enabled` (bool) - Enable alignment
- `AcrossEmptyLines` (bool) - Align across empty lines
- `AcrossComments` (bool) - Align across comments
- `AlignCompound` (bool) - Align compound assignments
- `PadOperators` (bool) - Pad operators to right
**Examples:**
`Enabled: true`:
```cpp
int a = 1;
int somelongname = 2;
double c = 3;
```
`Enabled: true, AcrossEmptyLines: true`:
```cpp
int a = 1;
int somelongname = 2;
double c = 3;
int d = 4;
```
`Enabled: true, AlignCompound: true`:
```cpp
a &= 2;
bbb = 2;
```
`Enabled: true, PadOperators: true`:
```cpp
a >>= 2;
bbb = 2;
```
**Shorthand:**
```yaml
# Boolean shorthand
AlignConsecutiveAssignments: true
# Full control
AlignConsecutiveAssignments:
Enabled: true
AcrossEmptyLines: false
AcrossComments: true
AlignCompound: true
PadOperators: true
```
### AlignConsecutiveBitFields
Align consecutive bit field declarations.
**Type:** `AlignConsecutiveStyle`
**Example:**
```cpp
int aaaa : 1;
int b : 12;
int ccc : 8;
```
### AlignConsecutiveDeclarations
Align consecutive declarations.
**Type:** `AlignConsecutiveStyle` **Sub-options:**
- `Enabled` (bool) - Enable alignment
- `AcrossEmptyLines` (bool) - Align across empty lines
- `AcrossComments` (bool) - Align across comments
- `AlignFunctionDeclarations` (bool) - Align function declarations
- `AlignFunctionPointers` (bool) - Align function pointers
**Examples:**
`Enabled: true`:
```cpp
int aaaa = 12;
float b = 23;
std::string ccc;
```
`Enabled: true, AcrossEmptyLines: true`:
```cpp
int aaaa = 12;
float b = 23;
std::string ccc;
int d = 45;
```
`Enabled: true, AlignFunctionDeclarations: true`:
```cpp
unsigned int f1(void);
void f2(void);
size_t f3(void);
```
`Enabled: true, AlignFunctionPointers: true`:
```cpp
unsigned i;
int &r;
int *p;
int (*f)();
```
### AlignConsecutiveMacros
Align consecutive macro definitions.
**Type:** `AlignConsecutiveStyle`
**Examples:**
`Enabled: true`:
```cpp
#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
```
`Enabled: true, AcrossEmptyLines: true`:
```cpp
#define SHORT_NAME 42
#define LONGER_NAME 0x007f
#define EVEN_LONGER_NAME (2)
#define foo(x) (x * x)
```
### AlignConsecutiveShortCaseStatements
Align consecutive short case labels.
**Type:** `ShortCaseStatementsAlignmentStyle` **Sub-options:**
- `Enabled` (bool)
- `AcrossEmptyLines` (bool)
- `AcrossComments` (bool)
- `AlignCaseColons` (bool) - Align case colons
- `AlignCaseArrows` (bool) - Align case arrows (for languages like Verilog)
**Example:**
`Enabled: true`:
```cpp
switch (x) {
case 1: return "one";
case 2: return "two";
case 10: return "ten";
}
```
`Enabled: true, AlignCaseColons: true`:
```cpp
switch (x) {
case 1 : return "one";
case 2 : return "two";
case 10 : return "ten";
}
```
### AlignEscapedNewlines
Align escaped newlines in macros.
**Type:** `EscapedNewlineAlignmentStyle` **Values:**
- `DontAlign` - Don't align
- `Left` - Align to the left
- `Right` - Align to the right
- `LeftWithLastLine` - Align to left, but relative to last line
**Examples:**
`Left`:
```cpp
#define A \
int aaaa; \
int b; \
int dddddddddd;
```
`Right`:
```cpp
#define A \
int aaaa; \
int b; \
int dddddddddd;
```
### AlignOperands
Align operands of binary and ternary expressions.
**Type:** `OperandAlignmentStyle` **Values:**
- `DontAlign` - Don't align
- `Align` - Align operands
- `AlignAfterOperator` - Align after operators
**Examples:**
`Align`:
```cpp
int aaa = bbbbbbbbbbbbbbb +
ccccccccccccccc;
```
`AlignAfterOperator`:
```cpp
int aaa = bbbbbbbbbbbbbbb
+ ccccccccccccccc;
```
### AlignTrailingComments
Align trailing comments.
**Type:** `TrailingCommentsAlignmentStyle` **Sub-options:**
- `Kind` - Alignment kind (Leave, Always, Never)
- `OverEmptyLines` - Lines to align over
**Examples:**
`Kind: Always`:
```cpp
int a; // Comment a
int b = 2; // Comment b
```
`Kind: Always, OverEmptyLines: 1`:
```cpp
int a; // Comment a
int b; // Comment b (aligned with comment a)
```
**Shorthand:**
```yaml
# Boolean shorthand
AlignTrailingComments: true
# Full control
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
```
## TableGen-Specific Alignment
These options apply specifically to LLVM TableGen code.
### AlignConsecutiveTableGenBreakingDAGArgColons
Align colons in breaking DAG arguments.
**Type:** `AlignConsecutiveStyle`
### AlignConsecutiveTableGenCondOperatorColons
Align colons in condition operators.
**Type:** `AlignConsecutiveStyle`
### AlignConsecutiveTableGenDefinitionColons
Align colons in definitions.
**Type:** `AlignConsecutiveStyle`
## Common Patterns
### Minimal Alignment (Performance-Focused)
```yaml
AlignAfterOpenBracket: DontAlign
AlignConsecutiveAssignments: false
AlignConsecutiveBitFields: false
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: false
AlignEscapedNewlines: DontAlign
AlignOperands: DontAlign
AlignTrailingComments: false
```
### Maximum Alignment (Readability-Focused)
```yaml
AlignAfterOpenBracket: Align
AlignArrayOfStructures: Left
AlignConsecutiveAssignments:
Enabled: true
AcrossEmptyLines: true
AcrossComments: true
AlignCompound: true
PadOperators: true
AlignConsecutiveBitFields:
Enabled: true
AlignConsecutiveDeclarations:
Enabled: true
AlignFunctionDeclarations: true
AlignFunctionPointers: true
AlignConsecutiveMacros:
Enabled: true
AcrossEmptyLines: true
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 1
```
### Moderate Alignment (Balanced)
```yaml
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveBitFields: true
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: true
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments: true
```
## Tips
1. **Performance Impact**: Extensive alignment can make diffs noisier and may slow formatting slightly
2. **Maintenance**: Aligned code may require more adjustments when making changes
3. **Consistency**: Choose alignment settings that match your team's preferences
4. **Selective Use**: Consider aligning only specific elements (e.g., macros but not assignments)
5. **Empty Lines**: Use `AcrossEmptyLines` carefully as it can create large alignment blocks
## See Also
- [Breaking & Line Wrapping](02-breaking.md) - Control where lines break
- [Indentation](04-indentation.md) - Control indentation behavior
- [Spacing](05-spacing.md) - Fine-tune whitespace
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Back to Index](index.md) | [CLI Usage](cli-usage.md) | [Next: Breaking →](02-breaking.md)

View File

@@ -0,0 +1,902 @@
# Breaking & Line Wrapping Options
[← Prev: Alignment](01-alignment.md) | [Back to Index](index.md) | [Next: Braces →](03-braces.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Control where lines break and how code wraps when it exceeds column limits.
## Overview
Breaking options determine where and how clang-format inserts line breaks. These options work together with `ColumnLimit` to control code width and readability.
## Column Limit
### ColumnLimit
Maximum line length before wrapping.
**Type:** `Unsigned` **Default:** `80`
```yaml
ColumnLimit: 100 # 100 characters per line
ColumnLimit: 0 # No limit
```
**Example:**
```cpp
// ColumnLimit: 80
void function(int param1,
int param2,
int param3);
// ColumnLimit: 120
void function(int param1, int param2, int param3);
```
## Allow Short Constructs on Single Line
These options control when short code blocks can remain on one line.
### AllowShortBlocksOnASingleLine
**Type:** `ShortBlockStyle` **Values:**
- `Never` - Never merge blocks into single line
- `Empty` - Only merge empty blocks
- `Always` - Always merge short blocks
**Examples:**
`Never`:
```cpp
while (true) {
}
while (true) {
continue;
}
```
`Empty`:
```cpp
while (true) {}
while (true) {
continue;
}
```
`Always`:
```cpp
while (true) {}
while (true) { continue; }
```
### AllowShortCaseLabelsOnASingleLine
Keep short case labels on a single line.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
switch (a) {
case 1: x = 1; break;
case 2: return;
}
```
`false`:
```cpp
switch (a) {
case 1:
x = 1;
break;
case 2:
return;
}
```
### AllowShortEnumsOnASingleLine
Keep short enums on a single line.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
enum { A, B } myEnum;
enum class Color { Red, Green, Blue };
```
`false`:
```cpp
enum {
A,
B
} myEnum;
enum class Color {
Red,
Green,
Blue
};
```
### AllowShortFunctionsOnASingleLine
**Type:** `ShortFunctionStyle` **Values:**
- `None` - Never merge functions
- `InlineOnly` - Only merge functions defined inside a class
- `Empty` - Only merge empty functions
- `Inline` - Merge inline and functions defined in class
- `All` - Merge all functions
**Examples:**
`InlineOnly`:
```cpp
class Foo {
void f() { foo(); }
};
void f() {
foo();
}
```
`Empty`:
```cpp
void f() {}
void f2() {
bar();
}
```
`All`:
```cpp
class Foo {
void f() { foo(); }
};
void f() { bar(); }
```
### AllowShortIfStatementsOnASingleLine
**Type:** `ShortIfStyle` **Values:**
- `Never` - Never put short ifs on one line
- `WithoutElse` - Only if without else
- `OnlyFirstIf` - Only first if without else
- `AllIfsAndElse` - All short if/else on one line
**Examples:**
`Never`:
```cpp
if (a)
return;
if (b)
return;
else
return;
```
`WithoutElse`:
```cpp
if (a) return;
if (b)
return;
else
return;
```
`AllIfsAndElse`:
```cpp
if (a) return;
if (b) return;
else return;
```
### AllowShortLambdasOnASingleLine
**Type:** `ShortLambdaStyle` **Values:**
- `None` - Never merge lambdas
- `Empty` - Only empty lambdas
- `Inline` - Lambdas inside function calls
- `All` - All lambdas
**Examples:**
`None`:
```cpp
auto lambda = []() {
return 1;
};
```
`Empty`:
```cpp
auto lambda = []() {};
auto lambda2 = []() {
return 1;
};
```
`All`:
```cpp
auto lambda = []() { return 1; };
```
### AllowShortLoopsOnASingleLine
Keep short loops on a single line.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
while (true) continue;
for (int i = 0; i < 10; ++i) {}
```
`false`:
```cpp
while (true)
continue;
for (int i = 0; i < 10; ++i) {
}
```
## Breaking Before/After Elements
### BreakBeforeBinaryOperators
Where to wrap binary operators.
**Type:** `BinaryOperatorStyle` **Values:**
- `None` - Break after operators
- `NonAssignment` - Break before non-assignment operators
- `All` - Break before all binary operators
**Examples:**
`None`:
```cpp
LooooooooooongType loooooooooooooooooooooongVariable =
someLooooooooooooooooongFunction();
bool value = aaaaaaaaaaaaaaaaaaaaa +
aaaaaaaaaaaaaaaaaaa ==
aaaaaaaaaaaaaaaaaaaaaaa &&
```
`NonAssignment`:
```cpp
LooooooooooongType loooooooooooooooooooooongVariable =
someLooooooooooooooooongFunction();
bool value = aaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa
== aaaaaaaaaaaaaaaaaaaaaaa
&& aaaaaaaaaaaaaaaaaaaaaaaa;
```
`All`:
```cpp
LooooooooooongType loooooooooooooooooooooongVariable
= someLooooooooooooooooongFunction();
bool value = aaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa
== aaaaaaaaaaaaaaaaaaaaaaa
&& aaaaaaaaaaaaaaaaaaaaaaaa;
```
### BreakBeforeTernaryOperators
Break before ternary operators.
**Type:** `Boolean`
**Examples:**
`true`:
```cpp
veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription
? firstValue
: secondValue;
```
`false`:
```cpp
veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongDescription ?
firstValue :
secondValue;
```
### BreakBinaryOperations
**Type:** `BreakBinaryOperationsStyle` **Since:** clang-format 20
The break binary operations style to use.
**Values:**
- `Never` - Don't break binary operations
- `OnePerLine` - Binary operations will either be all on same line, or each operation will have one line each
- `RespectPrecedence` - Binary operations of a particular precedence that exceed the column limit will have one line each
**Examples:**
`Never`:
```cpp
aaa + bbbb * ccccc - ddddd +
eeeeeeeeeeeeeeee;
```
`OnePerLine`:
```cpp
aaa +
bbbb *
ccccc -
ddddd +
eeeeeeeeeeeeeeee;
```
`RespectPrecedence`:
```cpp
aaa +
bbbb * ccccc -
ddddd +
eeeeeeeeeeeeeeee;
```
### BreakConstructorInitializers
Break constructor initializers.
**Type:** `BreakConstructorInitializersStyle` **Values:**
- `BeforeColon` - Break before `:` and `,`
- `BeforeComma` - Break before `,`
- `AfterColon` - Break after `:`
**Examples:**
`BeforeColon`:
```cpp
Constructor()
: initializer1()
, initializer2()
```
`BeforeComma`:
```cpp
Constructor()
: initializer1(),
initializer2()
```
`AfterColon`:
```cpp
Constructor() :
initializer1(),
initializer2()
```
### BreakInheritanceList
Break inheritance list.
**Type:** `BreakInheritanceListStyle` **Values:**
- `BeforeColon` - Break before `:`
- `BeforeComma` - Break before `,`
- `AfterColon` - Break after `:`
- `AfterComma` - Break after `,`
**Examples:**
`BeforeColon`:
```cpp
class Foo
: Base1
, Base2
{};
```
`AfterColon`:
```cpp
class Foo :
Base1,
Base2
{};
```
### BreakStringLiterals
Allow breaking string literals.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
const char* x = "veryVeryVeryVeryVeryVe"
"ryVeryVeryVeryVeryVery"
"VeryLongString";
```
`false` (exceeds column limit):
```cpp
const char* x = "veryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryVeryLongString";
```
### BreakAdjacentStringLiterals
Break adjacent string literals.
**Type:** `Boolean` **Default:** `true`
**Example:**
`true`:
```cpp
return "Code" "Llama";
```
`false`:
```cpp
return "CodeLlama";
```
## Breaking Templates and Return Types
### BreakAfterReturnType
Control breaking after return types.
**Type:** `ReturnTypeBreakingStyle` **Values:**
- `None` - Automatic
- `All` - Always break after return type
- `TopLevel` - Break after top-level function return types
- `AllDefinitions` - Break after all definition return types
- `TopLevelDefinitions` - Break after top-level definition return types
**Examples:**
`None`:
```cpp
class A {
int f() { return 0; }
};
int f();
int f() { return 1; }
```
`All`:
```cpp
class A {
int
f() {
return 0;
}
};
int
f();
int
f() {
return 1;
}
```
`TopLevel`:
```cpp
class A {
int f() { return 0; }
};
int
f();
int
f() {
return 1;
}
```
### BreakTemplateDeclarations
Breaking around template declarations.
**Type:** `BreakTemplateDeclarationsStyle` **Values:**
- `No` - Don't force breaks
- `MultiLine` - Break multi-line template declarations
- `Yes` - Always break after template declaration
**Examples:**
`No`:
```cpp
template <typename T> T foo() {
}
template <typename T> T foo(int aaaaaaaaaaaaaaaaaaaaa,
int bbbbbbbbbbbbbbbbbbbbb) {
}
```
`MultiLine`:
```cpp
template <typename T> T foo() {
}
template <typename T>
T foo(int aaaaaaaaaaaaaaaaaaaaa,
int bbbbbbbbbbbbbbbbbbbbb) {
}
```
`Yes`:
```cpp
template <typename T>
T foo() {
}
template <typename T>
T foo(int aaaaaaaaaaaaaaaaaaaaa,
int bbbbbbbbbbbbbbbbbbbbb) {
}
```
### BreakAfterAttributes
Break after attributes.
**Type:** `AttributeBreakingStyle` **Values:**
- `Always` - Always break after attributes
- `Leave` - Leave as is
- `Never` - Never break after attributes
**Example:**
`Always`:
```cpp
[[nodiscard]]
int f();
[[gnu::const]] [[nodiscard]]
int g();
```
`Never`:
```cpp
[[nodiscard]] int f();
[[gnu::const]] [[nodiscard]] int g();
```
## Special Breaking Options
### BreakBeforeConceptDeclarations
Break before C++20 concept declarations.
**Type:** `BreakBeforeConceptDeclarationsStyle` **Values:**
- `Never` - Keep on same line
- `Allowed` - Break if needed
- `Always` - Always break
**Example:**
`Always`:
```cpp
template <typename T>
concept ...
```
`Never`:
```cpp
template <typename T> concept ...
```
### BreakBeforeTemplateCloser
**Type:** `Boolean` **Since:** clang-format 21
If `true`, break before a template closing bracket (`>`) when there is a line break after the matching opening bracket (`<`).
**Examples:**
`true`:
```cpp
template <typename Foo, typename Bar>
template <typename Foo,
typename Bar>
template <
typename Foo,
typename Bar
>
```
`false`:
```cpp
template <typename Foo, typename Bar>
template <typename Foo,
typename Bar>
template <
typename Foo,
typename Bar>
```
### BreakBeforeInlineASMColon
Break before inline ASM colon.
**Type:** `BreakBeforeInlineASMColonStyle` **Values:**
- `Never`, `OnlyMultiline`, `Always`
### BreakFunctionDefinitionParameters
Break function definition parameters.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
void functionDeclaration(int A, int B);
void functionDefinition(
int A,
int B
) {
// function body
}
```
## Parameter and Argument Control
### AllowAllArgumentsOnNextLine
Allow putting all arguments on the next line.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
callFunction(
a, b, c, d);
```
`false` (will try to fit some on same line):
```cpp
callFunction(a,
b, c, d);
```
### AllowAllParametersOfDeclarationOnNextLine
Allow all parameters of declaration on next line.
**Type:** `Boolean`
Similar to `AllowAllArgumentsOnNextLine` but for declarations.
### AllowBreakBeforeQtProperty
**Type:** `Boolean` **Since:** clang-format 22
Allow breaking before `Q_Property` keywords `READ`, `WRITE`, etc. as if they were preceded by a comma. This allows them to be formatted according to `BinPackParameters`.
### BinPackArguments
Pack function arguments together.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
void f() {
f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
}
```
`false`:
```cpp
void f() {
f(aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaa,
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);
}
```
### BinPackLongBracedList
**Type:** `Boolean` **Since:** clang-format 21
If `true`, overrides `BinPackArguments` when there are 20 or more items in a braced initializer list.
**Example:**
`false`:
```cpp
vector<int> x{
1,
2,
...,
20,
21};
```
`true`:
```cpp
vector<int> x{1, 2, ...,
20, 21};
```
### BinPackParameters
Pack function parameters together.
**Type:** `BinPackParametersStyle` **Values:**
- `BinPack` - Bin-pack parameters
- `OnePerLine` - All on current line if they fit, otherwise one per line
- `AlwaysOnePerLine` - Always put each parameter on its own line
**Examples:**
`BinPack`:
```cpp
void f(int a, int bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,
int ccccccccccccccccccccccccccccccccccccccccccc);
```
`OnePerLine`:
```cpp
void f(int a, int b, int c);
void f(int a,
int b,
int ccccccccccccccccccccccccccccccccccccc);
```
`AlwaysOnePerLine`:
```cpp
void f(int a,
int b,
int c);
```
## Common Patterns
### Conservative Breaking (Wide Lines)
```yaml
ColumnLimit: 120
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
AllowShortBlocksOnASingleLine: Always
BreakBeforeBinaryOperators: None
BinPackArguments: true
BinPackParameters: BinPack
```
### Aggressive Breaking (Narrow Lines)
```yaml
ColumnLimit: 80
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AllowShortBlocksOnASingleLine: Never
BreakBeforeBinaryOperators: All
BinPackArguments: false
BinPackParameters: Never
AlwaysBreakTemplateDeclarations: Yes
```
### Balanced Breaking
```yaml
ColumnLimit: 100
AllowShortFunctionsOnASingleLine: InlineOnly
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLoopsOnASingleLine: false
AllowShortBlocksOnASingleLine: Empty
BreakBeforeBinaryOperators: NonAssignment
BinPackArguments: true
BinPackParameters: BinPackFirstParameter
```
## See Also
- [Brace Styles](03-braces.md) - Configure brace placement
- [Indentation](04-indentation.md) - Control indentation
- [Alignment](01-alignment.md) - Align code elements
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Alignment](01-alignment.md) | [Back to Index](index.md) | [Next: Braces →](03-braces.md)

View File

@@ -0,0 +1,929 @@
# Brace Styles
[← Prev: Breaking](02-breaking.md) | [Back to Index](index.md) | [Next: Indentation →](04-indentation.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Configure brace placement and wrapping for various code constructs.
## Overview
Brace style is one of the most visible formatting choices. clang-format supports all major brace styles through the `BreakBeforeBraces` option and fine-grained control via `BraceWrapping`.
## BreakBeforeBraces
The main option controlling brace style.
**Type:** `BraceBreakingStyle`
### Predefined Styles
#### Attach (K&R style)
```cpp
namespace N {
class C {
void f() {
if (x) {
} else {
}
}
};
}
```
#### Linux
```cpp
namespace N
{
class C
{
void f()
{
if (x) {
} else {
}
}
};
}
```
#### Mozilla
```cpp
namespace N {
class C
{
void f()
{
if (x) {
} else {
}
}
};
}
```
#### Stroustrup
```cpp
namespace N {
class C {
void f()
{
if (x) {
}
else {
}
}
};
}
```
#### Allman
```cpp
namespace N
{
class C
{
void f()
{
if (x)
{
}
else
{
}
}
};
}
```
#### Whitesmiths
```cpp
namespace N
{
class C
{
void f()
{
if (x)
{
}
else
{
}
}
};
}
```
#### GNU
```cpp
namespace N
{
class C
{
void f()
{
if (x)
{
}
else
{
}
}
};
}
```
#### WebKit
```cpp
namespace N {
class C {
void f()
{
if (x) {
} else {
}
}
};
}
```
#### Custom
Use `Custom` to configure individual brace wrapping with `BraceWrapping`.
```yaml
BreakBeforeBraces: Custom
BraceWrapping:
AfterFunction: true
AfterControlStatement: Never
# ... more options
```
## BraceWrapping
Fine-grained control over brace wrapping when `BreakBeforeBraces: Custom`.
**Type:** `BraceWrappingFlags`
### Sub-Options
#### AfterCaseLabel
Wrap case labels.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
switch (foo)
{
case 1:
{
bar();
break;
}
default:
{
plop();
}
}
```
`false`:
```cpp
switch (foo) {
case 1: {
bar();
break;
}
default: {
plop();
}
}
```
#### AfterClass
Wrap class definitions.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
class foo
{};
```
`false`:
```cpp
class foo {};
```
#### AfterControlStatement
Wrap control statements (if/for/while/switch).
**Type:** `BraceWrappingAfterControlStatementStyle` **Values:**
- `Never` - Never wrap
- `MultiLine` - Wrap if multi-line
- `Always` - Always wrap
**Examples:**
`Never`:
```cpp
if (foo) {
} else {
}
for (int i = 0; i < 10; ++i) {
}
```
`MultiLine`:
```cpp
if (foo) {
} else {
}
for (int i = 0; i < 10; ++i)
{
}
```
`Always`:
```cpp
if (foo)
{
}
else
{
}
for (int i = 0; i < 10; ++i)
{
}
```
#### AfterEnum
Wrap enum definitions.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
enum X : int
{
B
};
```
`false`:
```cpp
enum X : int { B };
```
#### AfterFunction
Wrap function definitions.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
void foo()
{
bar();
}
```
`false`:
```cpp
void foo() {
bar();
}
```
#### AfterNamespace
Wrap namespace definitions.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
namespace
{
int foo();
}
```
`false`:
```cpp
namespace {
int foo();
}
```
#### AfterStruct
Wrap struct definitions.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
struct foo
{
int x;
};
```
`false`:
```cpp
struct foo {
int x;
};
```
#### AfterUnion
Wrap union definitions.
**Type:** `Boolean`
Similar to `AfterStruct`.
#### AfterExternBlock
Wrap extern blocks.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
extern "C"
{
int foo();
}
```
`false`:
```cpp
extern "C" {
int foo();
}
```
#### AfterObjCDeclaration
Wrap ObjC definitions (interfaces, implementations...).
**Type:** `Boolean`
**Note:** `@autoreleasepool` and `@synchronized` blocks are wrapped according to `AfterControlStatement` flag.
#### BeforeCatch
Wrap before catch.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
try {
foo();
}
catch () {
}
```
`false`:
```cpp
try {
foo();
} catch () {
}
```
#### BeforeElse
Wrap before else.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
if (foo()) {
}
else {
}
```
`false`:
```cpp
if (foo()) {
} else {
}
```
#### BeforeLambdaBody
Wrap before lambda body.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
connect(
[]()
{
foo();
bar();
});
```
`false`:
```cpp
connect(
[]() {
foo();
bar();
});
```
#### BeforeWhile
Wrap before while in do-while.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
do {
foo();
}
while (1);
```
`false`:
```cpp
do {
foo();
} while (1);
```
#### IndentBraces
Indent wrapped braces themselves.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
void foo()
{
if (true)
{
}
}
```
`false`:
```cpp
void foo()
{
if (true)
{
}
}
```
#### SplitEmptyFunction
Split empty functions.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
int f()
{
}
```
`false`:
```cpp
int f() {}
```
#### SplitEmptyRecord
Split empty classes/structs.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
class Foo
{
}
```
`false`:
```cpp
class Foo {}
```
#### SplitEmptyNamespace
Split empty namespaces.
**Type:** `Boolean`
Similar to `SplitEmptyRecord`.
## Related Options
### BracedInitializerIndentWidth
Indent width for braced initializers.
**Type:** `Integer` **Default:** If unset or negative, `ContinuationIndentWidth` is used
**Example:**
`BracedInitializerIndentWidth: 2`:
```cpp
void f() {
SomeClass c{
"foo",
"bar",
"baz",
};
auto s = SomeStruct{
.foo = "foo",
.bar = "bar",
.baz = "baz",
};
SomeArrayT a[3] = {
{
foo,
bar,
},
{
foo,
bar,
},
SomeArrayT{},
};
}
```
### InsertBraces
Automatically insert optional braces after control statements.
**Type:** `Boolean` **Default:** `false`
**Example:**
`true`:
```cpp
if (isa<FunctionDecl>(D)) {
handleFunctionDecl(D);
} else if (isa<VarDecl>(D)) {
handleVarDecl(D);
} else {
return;
}
while (i--) {
for (auto *A : D.attrs()) {
handleAttr(A);
}
}
do {
--i;
} while (i);
```
`false`:
```cpp
if (isa<FunctionDecl>(D))
handleFunctionDecl(D);
else if (isa<VarDecl>(D))
handleVarDecl(D);
else
return;
while (i--)
for (auto *A : D.attrs())
handleAttr(A);
do
--i;
while (i);
```
**Warning:** 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. 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.
### RemoveBracesLLVM
Remove optional braces of control statements according to the LLVM coding style.
**Type:** `Boolean` **Default:** `false`
**Example:**
`true`:
```cpp
if (isa<FunctionDecl>(D))
handleFunctionDecl(D);
else if (isa<VarDecl>(D))
handleVarDecl(D);
if (isa<VarDecl>(D)) {
for (auto *A : D.attrs())
if (shouldProcessAttr(A))
handleAttr(A);
}
if (isa<FunctionDecl>(D))
for (auto *A : D.attrs())
handleAttr(A);
if (auto *D = (T)(D)) {
if (shouldProcess(D))
handleVarDecl(D);
else
markAsIgnored(D);
}
if (a)
b();
else if (c)
d();
else
e();
```
`false`:
```cpp
if (isa<FunctionDecl>(D)) {
handleFunctionDecl(D);
} else if (isa<VarDecl>(D)) {
handleVarDecl(D);
}
if (isa<VarDecl>(D)) {
for (auto *A : D.attrs()) {
if (shouldProcessAttr(A)) {
handleAttr(A);
}
}
}
if (isa<FunctionDecl>(D)) {
for (auto *A : D.attrs()) {
handleAttr(A);
}
}
if (auto *D = (T)(D)) {
if (shouldProcess(D)) {
handleVarDecl(D);
} else {
markAsIgnored(D);
}
}
if (a) {
b();
} else {
if (c) {
d();
} else {
e();
}
}
```
**Warning:** Remove optional braces of control statements (`if`, `else`, `for`, and `while`) in C++ according to the LLVM coding style. This option will be renamed and expanded to support other styles. 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.
## Common Brace Styles
### K&R / Kernel Style (Attach)
```yaml
BreakBeforeBraces: Attach
```
```cpp
int foo() {
if (true) {
return 0;
} else {
return 1;
}
}
```
### Allman / BSD Style
```yaml
BreakBeforeBraces: Allman
```
```cpp
int foo()
{
if (true)
{
return 0;
}
else
{
return 1;
}
}
```
### Stroustrup Style
```yaml
BreakBeforeBraces: Stroustrup
```
```cpp
int foo()
{
if (true) {
return 0;
}
else {
return 1;
}
}
```
### Linux Kernel Style
```yaml
BreakBeforeBraces: Linux
```
```cpp
namespace N
{
int foo()
{
if (true) {
return 0;
} else {
return 1;
}
}
}
```
### Custom: Functions Only
```yaml
BreakBeforeBraces: Custom
BraceWrapping:
AfterFunction: true
AfterClass: false
AfterStruct: false
AfterControlStatement: Never
BeforeElse: false
BeforeCatch: false
```
```cpp
class Foo {
void bar()
{
if (x) {
} else {
}
}
};
```
### Custom: Maximum Wrapping
```yaml
BreakBeforeBraces: Custom
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: Always
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: true
BeforeCatch: true
BeforeElse: true
BeforeLambdaBody: true
BeforeWhile: true
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
```
## Tips
1. **Consistency**: Choose one style and stick with it across your project
2. **Team Preference**: Match your team's existing conventions
3. **Language Idioms**: Some languages have stronger conventions (e.g., Java typically uses Attach style)
4. **Readability**: Consider what's most readable for your codebase's complexity
5. **Diff Size**: Styles with more wrapping create larger diffs when changing code
## See Also
- [Breaking & Line Wrapping](02-breaking.md) - Control line breaks
- [Indentation](04-indentation.md) - Control indentation within braces
- [Quick Reference](quick-reference.md) - Complete configuration examples
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Breaking](02-breaking.md) | [Back to Index](index.md) | [Next: Indentation →](04-indentation.md)

View File

@@ -0,0 +1,622 @@
# Indentation Options
[← Prev: Braces](03-braces.md) | [Back to Index](index.md) | [Next: Spacing →](05-spacing.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Control indentation behavior for various code constructs.
## Basic Indentation
### IndentWidth
Number of columns for each indentation level.
**Type:** `Unsigned` **Default:** `2`
```yaml
IndentWidth: 4
```
**Example:**
```cpp
void function() {
if (condition) {
doSomething();
}
}
```
### UseTab
The way to use tab characters in the resulting file.
**Type:** `UseTabStyle` **Values:**
- `Never` - Never use tab
- `ForIndentation` - Use tabs only for indentation
- `ForContinuationAndIndentation` - Fill all leading whitespace with tabs, and use spaces for alignment that appears within a line (e.g. consecutive assignments and declarations)
- `AlignWithSpaces` - Use tabs for line continuation and indentation, and spaces for alignment
- `Always` - Use tabs whenever we need to fill whitespace that spans at least from one tab stop to the next one
**Examples:**
`Never`:
```cpp
void f() {
int i;
}
```
`ForIndentation`:
```cpp
void f() {
int i;
}
```
`Always`:
```cpp
void f() {
int i;
}
```
### TabWidth
Visual width of a tab character.
**Type:** `Unsigned` **Default:** `8`
```yaml
TabWidth: 4
```
Affects how existing tabs are displayed and formatted.
### ContinuationIndentWidth
Indent for line continuations.
**Type:** `Unsigned` **Default:** `4`
```yaml
ContinuationIndentWidth: 4
```
**Example:**
```cpp
int var = function1() +
function2();
result = longFunction(
parameter1,
parameter2);
```
## Access Modifiers
### AccessModifierOffset
Offset for access modifiers (public, private, protected).
**Type:** `Integer` **Default:** `0`
Negative values indent left, positive values indent right.
**Examples:**
`AccessModifierOffset: -2`:
```cpp
class C {
public:
void f();
};
```
`AccessModifierOffset: 0`:
```cpp
class C {
public:
void f();
};
```
`AccessModifierOffset: 2`:
```cpp
class C {
public:
void f();
};
```
### IndentAccessModifiers
Indent access modifiers
.
**Type:** `Boolean` **Default:** `false`
**Example:**
`true`:
```cpp
class C {
public:
void f();
};
```
`false`:
```cpp
class C {
public:
void f();
};
```
## Case Labels and Switch
### IndentCaseLabels
Indent case labels from switch statement.
**Type:** `Boolean` **Default:** `false`
**Examples:**
`false`:
```cpp
switch (fool) {
case 1:
bar();
break;
default:
plop();
}
```
`true`:
```cpp
switch (fool) {
case 1:
bar();
break;
default:
plop();
}
```
### IndentCaseBlocks
Indent case blocks.
**Type:** `Boolean` **Default:** `false`
**Examples:**
`false`:
```cpp
switch (fool) {
case 1: {
bar();
} break;
default: {
plop();
}
}
```
`true`:
```cpp
switch (fool) {
case 1:
{
bar();
}
break;
default:
{
plop();
}
}
```
## Preprocessor Directives
### PPIndentWidth
Number of columns for preprocessor statement indentation.
**Type:** `Integer` **Default:** `-1` (uses `IndentWidth`)
```yaml
PPIndentWidth: 1
```
**Example:**
```cpp
#ifdef __linux__
# define FOO
#else
# define BAR
#endif
```
When set to -1 (default), `IndentWidth` is used also for preprocessor statements.
### IndentPPDirectives
Indent preprocessor directives.
**Type:** `PPDirectiveIndentStyle` **Values:**
- `None` - Don't indent directives
- `AfterHash` - Indent after the hash
- `BeforeHash` - Indent before the hash
- `Leave` - Leave indentation as-is (ignores `PPIndentWidth`)
**Examples:**
`None`:
```cpp
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
`AfterHash`:
```cpp
#if FOO
# if BAR
# include <foo>
# endif
#endif
```
`BeforeHash`:
```cpp
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
`Leave`:
```cpp
#if FOO
#if BAR
#include <foo>
#endif
#endif
```
## Special Constructs
### IndentGotoLabels
Indent goto labels.
**Type:** `Boolean` **Default:** `true`
**Examples:**
`true`:
```cpp
int f() {
if (foo()) {
label1:
bar();
}
label2:
return 1;
}
```
`false`:
```cpp
int f() {
if (foo()) {
label1:
bar();
}
label2:
return 1;
}
```
### IndentExternBlock
Indent extern blocks.
**Type:** `IndentExternBlockStyle` **Values:**
- `AfterExternBlock` - Indent after extern
- `NoIndent` - Don't indent
- `Indent` - Indent extern block
**Examples:**
`AfterExternBlock`:
```cpp
extern "C" {
void f();
}
extern "C"
{
void g();
}
```
`NoIndent`:
```cpp
extern "C" {
void f();
}
```
`Indent`:
```cpp
extern "C" {
void f();
}
```
### IndentRequiresClause
Indent C++20 requires clause. This only applies when `RequiresClausePosition` is `OwnLine`, `OwnLineWithBrace`, or `WithFollowing`.
**Type:** `Boolean`
Note: In clang-format 12, 13 and 14 this was named `IndentRequires`.
**Example:**
`true`:
```cpp
template <typename It>
requires Iterator<It>
void sort(It begin, It end) {
//....
}
```
`false`:
```cpp
template <typename It>
requires Iterator<It>
void sort(It begin, It end) {
//....
}
```
### IndentWrappedFunctionNames
Indent wrapped function names after line break.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
LoooooooooooooooooooooooooooooongReturnType
LoooooooooooooooooooongFunctionDeclaration();
```
`false`:
```cpp
LoooooooooooooooooooooooooooooongReturnType
LoooooooooooooooooooongFunctionDeclaration();
```
### ConstructorInitializerIndentWidth
Indent width for constructor initializers and inheritance lists.
**Type:** `Unsigned` **Default:** Uses `IndentWidth`
```yaml
ConstructorInitializerIndentWidth: 2
```
**Example:**
```cpp
Constructor()
: member1(),
member2() {}
```
### BracedInitializerIndentWidth
Number of columns to indent braced init list contents.
**Type:** `Integer` **Default:** Uses `ContinuationIndentWidth` if unset or negative **Since:** clang-format 17
```yaml
AlignAfterOpenBracket: AlwaysBreak
BracedInitializerIndentWidth: 2
```
**Example:**
```cpp
void f() {
SomeClass c{
"foo",
"bar",
"baz",
};
auto s = SomeStruct{
.foo = "foo",
.bar = "bar",
.baz = "baz",
};
SomeArrayT a[3] = {
{
foo,
bar,
},
{
foo,
bar,
},
SomeArrayT{},
};
}
```
## Language-Specific
### IndentExportBlock
Indent export blocks (JavaScript). 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.
**Type:** `Boolean` **Since:** clang-format 20
**Example:**
`true`:
```javascript
export { foo, bar };
```
`false`:
```javascript
export { foo, bar };
```
### ObjCBlockIndentWidth
Number of columns for indentation of ObjC blocks.
**Type:** `Unsigned`
```yaml
ObjCBlockIndentWidth: 4
```
**Example:**
```objc
[operation setCompletionBlock:^{
[self onOperationDone];
}];
```
## Common Patterns
### Minimal Indentation (2 spaces)
```yaml
IndentWidth: 2
UseTab: Never
ContinuationIndentWidth: 2
AccessModifierOffset: -2
IndentCaseLabels: false
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: None
IndentWrappedFunctionNames: false
```
### Standard Indentation (4 spaces)
```yaml
IndentWidth: 4
UseTab: Never
TabWidth: 4
ContinuationIndentWidth: 4
AccessModifierOffset: 0
IndentAccessModifiers: false
IndentCaseLabels: true
IndentCaseBlocks: false
IndentGotoLabels: true
IndentPPDirectives: AfterHash
PPIndentWidth: -1
IndentWrappedFunctionNames: true
BracedInitializerIndentWidth: 4
```
### Tab-Based Indentation
```yaml
IndentWidth: 4
UseTab: ForIndentation
TabWidth: 4
ContinuationIndentWidth: 4
AccessModifierOffset: -4
IndentCaseLabels: true
IndentPPDirectives: AfterHash
```
### Large Indentation (8 spaces, Linux style)
```yaml
IndentWidth: 8
UseTab: Always
TabWidth: 8
ContinuationIndentWidth: 8
AccessModifierOffset: -8
IndentCaseLabels: false
IndentGotoLabels: false
IndentPPDirectives: None
```
## Tips
1. **Consistency**: Use the same indentation throughout your project
2. **Tab Width**: If using tabs, ensure `TabWidth` matches team editor settings
3. **Continuation**: Set `ContinuationIndentWidth` to help distinguish continuations from blocks
4. **Access Modifiers**: Negative `AccessModifierOffset` creates outdent effect
5. **Preprocessor**: Be careful with `IndentPPDirectives` in complex macro code; use `PPIndentWidth` to control preprocessor indentation separately
6. **Mixed Tabs/Spaces**: Avoid mixing; use `Never` or `ForIndentation` for consistent results
7. **Braced Initializers**: Use `BracedInitializerIndentWidth` (clang-format 17+) to control indentation of braced init lists independently
8. **Leave Option**: The `Leave` value for `IndentPPDirectives` preserves existing preprocessor indentation without changes
## See Also
- [Alignment](01-alignment.md) - Align code elements
- [Spacing](05-spacing.md) - Control whitespace
- [Braces](03-braces.md) - Configure brace placement
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Braces](03-braces.md) | [Back to Index](index.md) | [Next: Spacing →](05-spacing.md)

View File

@@ -0,0 +1,797 @@
# Spacing Options
[← Prev: Indentation](04-indentation.md) | [Back to Index](index.md) | [Next: Includes →](06-includes.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Fine-tune whitespace placement throughout your code.
## Parentheses and Brackets
### SpaceBeforeParens
Add space before opening parentheses.
**Type:** `SpaceBeforeParensStyle` **Values:**
- `Never` - **Deprecated.** Use `Custom` with all `SpaceBeforeParensOptions` except `AfterPlacementOperator` set to `false`
- `ControlStatements` - Only before control statement parens
- `ControlStatementsExceptControlMacros` - Control statements except macros
- `NonEmptyParentheses` - Only if parentheses aren't empty
- `Always` - Always add space
- `Custom` - Use `SpaceBeforeParensOptions`
**Examples:**
`Never`:
```cpp
void f() {
if(true) {
f();
}
}
```
`ControlStatements`:
```cpp
void f() {
if (true) {
f();
}
}
```
`Always`:
```cpp
void f () {
if (true) {
f ();
}
}
```
### SpaceBeforeParensOptions
Fine-grained control when `SpaceBeforeParens: Custom`.
**Sub-options:**
- `AfterControlStatements` (bool) - Space between control statement keywords and opening parentheses
- `AfterForeachMacros` (bool) - Space between foreach macros and opening parentheses
- `AfterFunctionDeclarationName` (bool) - Space between function declaration name and opening parentheses
- `AfterFunctionDefinitionName` (bool) - Space between function definition name and opening parentheses
- `AfterIfMacros` (bool) - Space between if macros and opening parentheses
- `AfterOverloadedOperator` (bool) - Space between operator overloading and opening parentheses
- `AfterPlacementOperator` (bool) - Space between operator `new`/`delete` and opening parentheses
- `AfterRequiresInClause` (bool) - Space between requires keyword in requires clause and opening parentheses
- `AfterRequiresInExpression` (bool) - Space between requires keyword in requires expression and opening parentheses
- `BeforeNonEmptyParentheses` (bool) - Space before opening parentheses only if not empty
### SpacesInParens
Defines in which cases spaces will be inserted after `(` and before `)`.
**Type:** `SpacesInParensStyle` **Values:**
- `Never` - Never put a space in parentheses
- `Custom` - Use `SpacesInParensOptions`
**Example:**
`Never`:
```cpp
void f() {
if(true) {
f();
}
}
```
### SpacesInParensOptions
Control of individual spaces in parentheses when `SpacesInParens: Custom`.
**Sub-options:**
- `ExceptDoubleParentheses` (bool) - Override other options to prevent space when both opening and closing use multiple parentheses
- `InConditionalStatements` (bool) - Space in parentheses inside conditional statements
- `InCStyleCasts` (bool) - Space in C style casts
- `InEmptyParentheses` (bool) - Space in empty parentheses, i.e. `()`
- `Other` (bool) - Space in parentheses not covered by preceding options
**Example:**
```yaml
SpacesInParens: Custom
SpacesInParensOptions:
InConditionalStatements: true
Other: true
```
### SpacesInParentheses
**Deprecated:** Use `SpacesInParens` with `Custom` and set all `SpacesInParensOptions` to `true` except `InCStyleCasts` and `InEmptyParentheses`.
Add spaces inside parentheses.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
t f( Deleted & ) & = delete;
```
`false`:
```cpp
t f(Deleted &) & = delete;
```
### SpaceInEmptyParentheses
**Deprecated:** Use `InEmptyParentheses` in `SpacesInParensOptions`.
### SpacesInCStyleCastParentheses
**Deprecated:** Use `InCStyleCasts` in `SpacesInParensOptions`.
### SpacesInConditionalStatement
**Deprecated:** Use `InConditionalStatements` in `SpacesInParensOptions`.
### SpacesInSquareBrackets
Add spaces inside square brackets.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
int a[ 5 ];
```
`false`:
```cpp
int a[5];
```
### SpaceBeforeSquareBrackets
Add spaces before `[`.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
int a [5];
int a [5][5];
```
`false`:
```cpp
int a[5];
int a[5][5];
```
**Note:** Lambdas will not be affected. Only the first `[` gets a space.
### SpacesInAngles
Add spaces inside angle brackets.
**Type:** `SpacesInAnglesStyle` **Values:**
- `Never` - Remove spaces after `<` and before `>`
- `Always` - Add spaces after `<` and before `>`
- `Leave` - Keep a single space if any were present
**Example:**
`Always`:
```cpp
static_cast< int >(arg);
std::vector< int > vec;
```
## Operators and Assignments
### SpaceBeforeAssignmentOperators
Add space before assignment operators.
**Type:** `Boolean` **Default:** `true`
**Example:**
`true`:
```cpp
int a = 5;
a += 42;
```
`false`:
```cpp
int a= 5;
a+= 42;
```
### SpaceBeforeRangeBasedForLoopColon
Add space before colon in range-based for loop.
**Type:** `Boolean` **Default:** `true`
**Example:**
`true`:
```cpp
for (auto v : values) {}
```
`false`:
```cpp
for (auto v: values) {}
```
### SpaceInEmptyBlock
**Deprecated:** Use `Block` in `SpaceInEmptyBraces`.
Add space in empty blocks.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
void f() { }
while (true) { }
```
`false`:
```cpp
void f() {}
while (true) {}
```
### SpaceInEmptyBraces
Specifies when to insert a space in empty braces.
**Type:** `SpaceInEmptyBracesStyle` **Values:**
- `Always` - Always insert a space in empty braces
- `Block` - Only insert a space in empty blocks
- `Never` - Never insert a space in empty braces
**Note:** This option doesn't apply to initializer braces if `Cpp11BracedListStyle` is not `Block`.
**Examples:**
`Always`:
```cpp
void f() { }
class Unit { };
auto a = [] { };
int x{ };
```
`Block`:
```cpp
void f() { }
class Unit { };
auto a = [] { };
int x{};
```
`Never`:
```cpp
void f() {}
class Unit {};
auto a = [] {};
int x{};
```
## Casts and Templates
### SpaceAfterCStyleCast
Add space after C-style cast.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
(int) i;
```
`false`:
```cpp
(int)i;
```
### SpaceAfterLogicalNot
Add space after logical not operator (!).
**Type:** `Boolean`
**Example:**
`true`:
```cpp
! someExpression();
```
`false`:
```cpp
!someExpression();
```
### SpaceAfterTemplateKeyword
Add space after template keyword.
**Type:** `Boolean` **Default:** `true`
**Example:**
`true`:
```cpp
template <int> void foo();
```
`false`:
```cpp
template<int> void foo();
```
### SpaceBeforeCaseColon
Add space before case colon.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
switch (x) {
case 1 : break;
}
```
`false`:
```cpp
switch (x) {
case 1: break;
}
```
### SpaceBeforeCpp11BracedList
Add space before C++11 braced list.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
Foo foo { bar };
Foo {};
vector<int> { 1, 2, 3 };
new int[3] { 1, 2, 3 };
```
`false`:
```cpp
Foo foo{ bar };
Foo{};
vector<int>{ 1, 2, 3 };
new int[3]{ 1, 2, 3 };
```
### SpaceBeforeCtorInitializerColon
Add space before constructor initializer colon.
**Type:** `Boolean` **Default:** `true`
**Example:**
`true`:
```cpp
Foo::Foo() : a(a) {}
```
`false`:
```cpp
Foo::Foo(): a(a) {}
```
### SpaceBeforeInheritanceColon
Add space before inheritance colon.
**Type:** `Boolean` **Default:** `true`
**Example:**
`true`:
```cpp
class Foo : Bar {}
```
`false`:
```cpp
class Foo: Bar {}
```
### SpaceBeforeJsonColon
Add space before JSON colon.
**Type:** `Boolean`
**Example:**
`true`:
```javascript
{
"key" : "value"
}
```
`false`:
```javascript
{
"key": "value"
}
```
**Note:** For other languages like JavaScript, use `SpacesInContainerLiterals` instead.
## Containers and Comments
### SpacesBeforeTrailingComments
Number of spaces before trailing comments.
**Type:** `Unsigned` **Default:** `1`
**Example:**
`2`:
```cpp
void f() {
if (true) {
f(); // comment
} // comment
}
```
### SpacesInContainerLiterals
Add spaces in container literals.
**Type:** `Boolean`
**Example:**
`true` (JavaScript/JSON):
```javascript
var arr = [1, 2, 3];
obj = { a: 1, b: 2, c: 3 };
```
`false`:
```javascript
var arr = [1, 2, 3];
obj = { a: 1, b: 2, c: 3 };
```
**Note:** For JSON, use `SpaceBeforeJsonColon` instead.
### SpacesInLineCommentPrefix
Spaces in line comment prefix.
**Type:** `SpacesInLineComment` **Sub-options:**
- `Minimum` - Minimum spaces
- `Maximum` - Maximum spaces (use `-1` for no max)
**Example:**
`Minimum: 1, Maximum: -1` (no max):
```cpp
//A comment
// A comment
// A comment
```
### SpaceAroundPointerQualifiers
Configure spaces around pointer qualifiers.
**Type:** `SpaceAroundPointerQualifiersStyle` **Values:**
- `Default`, `Before`, `After`, `Both`
**Examples:**
`Default`:
```cpp
void* const* x = NULL;
```
`Before`:
```cpp
void *const *x = NULL;
```
`After`:
```cpp
void* const* x = NULL;
```
`Both`:
```cpp
void * const * x = NULL;
```
## Bit Fields
### BitFieldColonSpacing
Spacing around bit field colon.
**Type:** `BitFieldColonSpacingStyle` **Values:**
- `Both` - Add spaces on both sides
- `None` - No spaces
- `Before` - Space before only
- `After` - Space after only
**Examples:**
`Both`:
```cpp
unsigned bf : 2;
```
`None`:
```cpp
unsigned bf:2;
```
`Before`:
```cpp
unsigned bf :2;
```
`After`:
```cpp
unsigned bf: 2;
```
## Empty Lines
### MaxEmptyLinesToKeep
Maximum consecutive empty lines to keep.
**Type:** `Unsigned` **Default:** `1`
**Example:**
`1`:
```cpp
int f() {
int = 1;
return i;
}
```
`2`:
```cpp
int f() {
int i = 1;
return i;
}
```
### KeepEmptyLines
Which empty lines are kept.
**Type:** `KeepEmptyLinesStyle` **Sub-options:**
- `AtEndOfFile` (bool) - Keep empty lines at end of file
- `AtStartOfBlock` (bool) - Keep empty lines at start of blocks
- `AtStartOfFile` (bool) - Keep empty lines at start of file
**Note:** `MaxEmptyLinesToKeep` determines how many consecutive empty lines are kept.
**Example:**
```yaml
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: false
AtStartOfFile: false
```
### KeepEmptyLinesAtTheStartOfBlocks
**Deprecated:** Use `AtStartOfBlock` in `KeepEmptyLines`.
Keep empty lines at start of blocks.
**Type:** `Boolean` **Default:** `true`
**Example:**
`false`:
```cpp
void f() {
foo();
}
```
`true`:
```cpp
void f() {
foo();
}
```
### KeepEmptyLinesAtEOF
**Deprecated:** Use `AtEndOfFile` in `KeepEmptyLines`.
Keep empty lines at end of file.
**Type:** `Boolean`
## Common Patterns
### Minimal Spacing (Compact)
```yaml
SpaceBeforeParens: Never
SpaceBeforeAssignmentOperators: true
SpaceInEmptyBraces: Never
SpacesInParens: Never
SpacesInSquareBrackets: false
SpacesInAngles: Never
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpacesBeforeTrailingComments: 1
MaxEmptyLinesToKeep: 1
```
### Standard Spacing
```yaml
SpaceBeforeParens: ControlStatements
SpaceBeforeAssignmentOperators: true
SpaceInEmptyBraces: Never
SpacesInParens: Never
SpacesInSquareBrackets: false
SpacesInAngles: Never
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceBeforeCpp11BracedList: false
SpacesBeforeTrailingComments: 2
MaxEmptyLinesToKeep: 1
KeepEmptyLines:
AtStartOfBlock: false
```
### Generous Spacing (Readable)
```yaml
SpaceBeforeParens: ControlStatements
SpaceBeforeAssignmentOperators: true
SpaceInEmptyBraces: Always
SpacesInParens: Never
SpacesInSquareBrackets: false
SpacesInAngles: Never
SpaceAfterCStyleCast: true
SpaceAfterLogicalNot: true
SpaceAfterTemplateKeyword: true
SpaceBeforeCpp11BracedList: true
SpacesBeforeTrailingComments: 2
MaxEmptyLinesToKeep: 2
KeepEmptyLines:
AtStartOfBlock: true
```
## Tips
1. **Consistency**: Apply spacing rules uniformly across the codebase
2. **Readability**: More spaces can improve readability but increase line length
3. **Language Conventions**: Some languages have strong spacing conventions
4. **Trailing Comments**: Use at least 2 spaces before trailing comments for clarity
5. **Empty Lines**: Limit `MaxEmptyLinesToKeep` to prevent excessive whitespace
6. **Containers**: Enable `SpacesInContainerLiterals` for JSON/JavaScript readability
7. **Deprecations**: Prefer newer options like `SpacesInParens` over deprecated `SpacesInParentheses`
8. **Custom Control**: Use `Custom` settings with fine-grained options for precise control
## See Also
- [Alignment](01-alignment.md) - Align code elements
- [Indentation](04-indentation.md) - Control indentation
- [Breaking](02-breaking.md) - Control line breaks
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Indentation](04-indentation.md) | [Back to Index](index.md) | [Next: Includes →](06-includes.md)

View File

@@ -0,0 +1,395 @@
# Include Organization Options
[← Prev: Spacing](05-spacing.md) | [Back to Index](index.md) | [Next: Languages →](07-languages.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Organize and sort include directives automatically.
## Migration Note
**Important:** In Clang v22, `SortIncludes` has changed from a simple enum to a nested configuration structure:
- Old syntax (deprecated): `SortIncludes: Never|CaseSensitive|CaseInsensitive`
- New syntax:
```yaml
SortIncludes:
Enabled: true/false
IgnoreCase: true/false
IgnoreExtension: true/false
```
**Migration Guide:**
- `SortIncludes: Never` → `SortIncludes: { Enabled: false }`
- `SortIncludes: CaseSensitive` → `SortIncludes: { Enabled: true, IgnoreCase: false }`
- `SortIncludes: CaseInsensitive` → `SortIncludes: { Enabled: true, IgnoreCase: true }`
The old values are deprecated but still supported for backward compatibility.
## Enable Include Sorting
### SortIncludes
Controls if and how clang-format will sort `#includes`.
**Type:** `SortIncludesOptions` (nested configuration) **Suboptions:**
- `Enabled` (bool) - If `true`, includes are sorted based on other suboptions. Replaces deprecated `Never` value (use `Enabled: false` instead).
- `IgnoreCase` (bool) - Whether includes are sorted case-insensitively. Replaces deprecated `CaseSensitive` and `CaseInsensitive` values (use `IgnoreCase: false` and `IgnoreCase: true` respectively).
- `IgnoreExtension` (bool) - When sorting includes in each block, only take file extensions into account if two includes compare equal otherwise.
**Example:**
`IgnoreCase: false` (replaces `CaseSensitive`):
```cpp
#include "A/B.h"
#include "A/b.h"
#include "B/A.h"
#include "B/a.h"
#include "a/b.h"
```
`IgnoreCase: true` (replaces `CaseInsensitive`):
```cpp
#include "A/B.h"
#include "A/b.h"
#include "a/b.h"
#include "B/A.h"
#include "B/a.h"
```
`IgnoreExtension: true`:
```cpp
# include "A.h"
# include "A.inc"
# include "A-util.h"
```
`IgnoreExtension: false`:
```cpp
# include "A-util.h"
# include "A.h"
# include "A.inc"
```
**Configuration:**
```yaml
SortIncludes:
Enabled: true
IgnoreCase: false
IgnoreExtension: false
```
## Include Blocks
### IncludeBlocks
How to organize include blocks.
**Type:** `IncludeBlocksStyle` **Values:**
- `Preserve` - Keep existing blocks
- `Merge` - Merge all includes into one block
- `Regroup` - Separate into blocks by category
**Examples:**
`Preserve`:
```cpp
#include "b.h"
#include "a.h"
#include <lib/main.h>
```
`Merge`:
```cpp
#include "a.h"
#include "b.h"
#include <lib/main.h>
```
`Regroup`:
```cpp
#include "a.h"
#include "b.h"
#include <lib/main.h>
```
## Include Categories
### IncludeCategories
Define categories for organizing includes.
**Type:** `List of IncludeCategories`
**Structure:**
```yaml
IncludeCategories:
- Regex: "<[[:alnum:]]+>"
Priority: 1
- Regex: "<.*>"
Priority: 2
- Regex: ".*"
Priority: 3
```
**Fields:**
- `Regex` - Regular expression to match include path
- `Priority` - Sort priority (lower numbers first)
- `SortPriority` - Optional separate sort priority
- `CaseSensitive` - Optional case sensitivity flag
**Example Configuration:**
```yaml
IncludeBlocks: Regroup
IncludeCategories:
# Main header (for .cpp files)
- Regex: '^".*\.h"$'
Priority: 1
SortPriority: 1
# Project headers
- Regex: '^".*"$'
Priority: 2
SortPriority: 2
# System headers
- Regex: '^<.*\.h>$'
Priority: 3
SortPriority: 3
# C++ standard library
- Regex: "^<.*>$"
Priority: 4
SortPriority: 4
```
**Result:**
```cpp
#include "myclass.h"
#include "project/helper.h"
#include "project/utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <vector>
```
## Main Include Detection
### IncludeIsMainRegex
Regex to identify main include file.
**Type:** `String` **Default:** `([-_](test|unittest))?$`
Used to ensure the main header for a .cpp file sorts first.
**Example:**
For `foo.cpp`, these would be detected as main includes:
- `foo.h`
- `foo_test.h`
- `foo-unittest.h`
```yaml
IncludeIsMainRegex: "([-_](test|unittest))?$"
```
### IncludeIsMainSourceRegex
Additional regex for detecting source files.
**Type:** `String`
**Example:**
```yaml
IncludeIsMainSourceRegex: "(_test)?$"
```
This helps clang-format recognize test files as valid source files.
## Common Configurations
### C++ with Standard Library Priority
```yaml
SortIncludes:
Enabled: true
IgnoreCase: false
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^".*\.h"'
Priority: 1
- Regex: '^".*'
Priority: 2
- Regex: '^<.*\.h>'
Priority: 3
- Regex: "^<.*"
Priority: 4
IncludeIsMainRegex: "([-_](test|unittest))?$"
```
**Result:**
```cpp
// main.cpp
#include "main.h"
#include "project/module.h"
#include <sys/types.h>
#include <iostream>
#include <vector>
```
### Google C++ Style
```yaml
SortIncludes:
Enabled: true
IgnoreCase: false
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
SortPriority: 0
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 1
- Regex: "^<.*"
Priority: 2
SortPriority: 2
- Regex: ".*"
Priority: 3
SortPriority: 3
IncludeIsMainRegex: "([-_](test|unittest))?$"
```
### LLVM Style
```yaml
SortIncludes:
Enabled: true
IgnoreCase: false
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
- Regex: ".*"
Priority: 1
IncludeIsMainRegex: "(Test)?$"
IncludeIsMainSourceRegex: ""
```
### Mozilla Style
```yaml
SortIncludes:
Enabled: true
IgnoreCase: true
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^".*\.h"'
Priority: 1
- Regex: '^<.*\.h>'
Priority: 2
- Regex: "^<.*"
Priority: 3
- Regex: ".*"
Priority: 4
```
### Simple Three-Tier
```yaml
SortIncludes:
Enabled: true
IgnoreCase: false
IncludeBlocks: Regroup
IncludeCategories:
# Local headers
- Regex: '^"'
Priority: 1
# System headers
- Regex: '^<.*\.h>'
Priority: 2
# C++ standard library
- Regex: "^<"
Priority: 3
```
**Result:**
```cpp
#include "local.h"
#include <stdlib.h>
#include <sys/types.h>
#include <iostream>
#include <string>
```
## Tips
1. **Test Thoroughly**: Include sorting can be tricky; test on your entire codebase
2. **Main Header First**: Configure `IncludeIsMainRegex` to match your naming conventions
3. **Category Priority**: Lower priority numbers sort first
4. **Regex Matching**: Test your regex patterns carefully; they must match the full include path
5. **Case Sensitivity**: Match your filesystem's case sensitivity
6. **Block Separation**: Use `Regroup` for visual organization
7. **Gradual Adoption**: Consider `Preserve` initially, then migrate to `Regroup`
## Disabling Sorting
To disable include sorting for specific sections:
```cpp
// clang-format off
#include "z.h"
#include "a.h"
// clang-format on
```
Or globally:
```yaml
SortIncludes:
Enabled: false
```
Note: `SortIncludes: Never` is deprecated, use `Enabled: false` instead.
## See Also
- [CLI Usage](cli-usage.md) - Command-line options including `--sort-includes`
- [Comments & Misc](08-comments.md) - Comment-related options
- [Languages](07-languages.md) - Language-specific settings
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Spacing](05-spacing.md) | [Back to Index](index.md) | [Next: Languages →](07-languages.md)

View File

@@ -0,0 +1,480 @@
# Language-Specific Options
[← Prev: Includes](06-includes.md) | [Back to Index](index.md) | [Next: Comments →](08-comments.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Options that apply to specific programming languages.
## Language Selection
### Language
Specify the language for formatting.
**Type:** `LanguageKind` **Values:**
- `None` - Do not use
- `C` - C
- `Cpp` - C++
- `CSharp` - C#
- `Java` - Java
- `JavaScript` - JavaScript
- `Json` - JSON
- `ObjC` - Objective-C, Objective-C++
- `Proto` - Protocol Buffers
- `TableGen` - LLVM TableGen
- `TextProto` - Text format Protocol Buffers
- `Verilog` - Verilog/SystemVerilog
**Note:** For `.h` files, specify the language explicitly with a comment:
```cpp
// clang-format Language: Cpp
```
**Usage:**
In `.clang-format`:
```yaml
---
Language: Cpp
# C++ options
---
Language: JavaScript
# JavaScript options
---
```
## JavaScript/TypeScript
### JavaScriptQuotes
Quote style for JavaScript strings.
**Type:** `JavaScriptQuoteStyle` **Values:**
- `Leave` - Keep existing quotes
- `Single` - Use single quotes
- `Double` - Use double quotes
**Example:**
`Single`:
```javascript
import { a } from "foo";
let x = "hello";
```
`Double`:
```javascript
import { a } from "foo";
let x = "hello";
```
### JavaScriptWrapImports
Wrap ES6 import/export statements.
**Type:** `Boolean`
**Example:**
`true`:
```javascript
import { VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying } from "some/module.js";
```
`false`:
```javascript
import { VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying, VeryLongImportsAreAnnoying } from "some/module.js";
```
### BreakArrays
Break after JSON array opening bracket `[`.
**Type:** `Boolean`
**Note:** This is currently only for formatting JSON. When `true`, clang-format will always break after a JSON array `[`. When `false`, it will scan until the closing `]` to determine if it should add newlines between elements (prettier compatible).
**Example:**
`true`:
```json
[1, 2, 3, 4]
```
`false`:
```json
[1, 2, 3, 4]
```
## Java
### JavaImportGroups
Define Java import groups.
**Type:** `List of Strings`
**Example:**
```yaml
JavaImportGroups:
- com.mycompany
- com
- org
```
**Result:**
```java
import com.mycompany.Foo;
import com.mycompany.Bar;
import com.otherlibrary.Baz;
import org.apache.Something;
```
### BreakAfterJavaFieldAnnotations
Break after field annotations in Java.
**Type:** `Boolean`
**Example:**
`true`:
```java
@Annotation
private int myField;
```
`false`:
```java
@Annotation private int myField;
```
### SortJavaStaticImport
Control placement of static imports relative to non-static imports.
**Type:** `SortJavaStaticImportOptions` **Values:**
- `Before` - Static imports are placed before non-static imports (default)
- `After` - Static imports are placed after non-static imports
**Example:**
`Before`:
```java
import static org.example.function1;
import org.example.ClassA;
```
`After`:
```java
import org.example.ClassA;
import static org.example.function1;
```
**Note:** This option works in conjunction with `JavaImportGroups` to control Java import organization.
## C
C# uses the `CSharp` language setting and shares most options with other C-family languages.
## Protocol Buffers
Protocol buffer files use the `Proto` or `TextProto` language settings.
**Example Configuration:**
```yaml
---
Language: Proto
BasedOnStyle: Google
IndentWidth: 2
---
Language: TextProto
BasedOnStyle: Google
---
```
## TableGen (LLVM)
TableGen has specific alignment options (see [Alignment](01-alignment.md)):
- `AlignConsecutiveTableGenBreakingDAGArgColons`
- `AlignConsecutiveTableGenCondOperatorColons`
- `AlignConsecutiveTableGenDefinitionColons`
## Objective-C
### ObjCBinPackProtocolList
Pack Objective-C protocol list.
**Type:** `BinPackStyle` **Values:**
- `Auto`, `Always`, `Never`
**Example:**
`Never`:
```objc
@interface ccccccccccccc () <
ccccccccccccc,
ccccccccccccc,
ccccccccccccc,
ccccccccccccc>
```
`Always`:
```objc
@interface ccccccccccccc () <ccccccccccccc, ccccccccccccc, ccccccccccccc, ccccccccccccc>
```
### ObjCBlockIndentWidth
Indent width for ObjC blocks.
**Type:** `Unsigned`
### ObjCBreakBeforeNestedBlockParam
Break before nested block parameters.
**Type:** `Boolean`
### ObjCPropertyAttributeOrder
Order of Objective-C property attributes.
**Type:** `List of Strings`
**Example:**
```yaml
ObjCPropertyAttributeOrder:
[
class,
direct,
atomic,
nonatomic,
assign,
retain,
strong,
copy,
weak,
unsafe_unretained,
readonly,
readwrite,
getter,
setter,
nullable,
nonnull,
null_resettable,
null_unspecified,
]
```
**Warning:** Using this option could lead to incorrect code formatting due to clang-format's lack of complete semantic information. Extra care should be taken to review code changes.
### ObjCSpaceAfterProperty
Add space after @property.
**Type:** `Boolean`
**Example:**
`true`:
```objc
@property (readonly) int a;
```
`false`:
```objc
@property(readonly) int a;
```
### ObjCSpaceBeforeProtocolList
Add space before protocol list.
**Type:** `Boolean`
**Example:**
`true`:
```objc
Foo <Protocol> *foo;
```
`false`:
```objc
Foo<Protocol> *foo;
```
## Verilog/SystemVerilog
### VerilogBreakBetweenInstancePorts
Break between instance ports.
**Type:** `Boolean`
## Multi-Language Configuration
Use separate sections for different languages:
```yaml
---
# C++ configuration
Language: Cpp
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 100
---
# JavaScript configuration
Language: JavaScript
BasedOnStyle: Google
IndentWidth: 2
JavaScriptQuotes: Single
JavaScriptWrapImports: true
---
# JSON configuration
Language: Json
IndentWidth: 2
BreakArrays: true
---
# Java configuration
Language: Java
BasedOnStyle: Google
JavaImportGroups:
- com.mycompany
- com
- org
---
```
## Language Detection
clang-format detects language from file extension:
- `.c` → C
- `.cpp`, `.cc`, `.cxx`, `.h`, `.hpp` → Cpp
- `.cs` → CSharp
- `.java` → Java
- `.js`, `.mjs`, `.ts` → JavaScript
- `.json`, `.ipynb` → Json
- `.m`, `.mm` → ObjC
- `.proto` → Proto
- `.td` → TableGen
- `.txtpb`, `.textproto` → TextProto
- `.sv`, `.v`, `.vh` → Verilog
**Note:** For `.h` files that could be C, C++, or Objective-C, add a language comment at the top of the file to ensure correct detection.
Override with `--assume-filename`:
```bash
cat file.txt | clang-format --assume-filename=file.cpp
```
## Common Patterns
### JavaScript/TypeScript Project
```yaml
---
Language: JavaScript
BasedOnStyle: Google
IndentWidth: 2
ColumnLimit: 100
JavaScriptQuotes: Single
JavaScriptWrapImports: true
SpacesInContainerLiterals: true
---
```
### Java Enterprise Project
```yaml
---
Language: Java
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 120
JavaImportGroups:
- com.company.product
- com.company
- java
- javax
BreakAfterJavaFieldAnnotations: true
---
```
### Multi-Language Monorepo
```yaml
---
Language: Cpp
BasedOnStyle: Google
IndentWidth: 2
---
Language: JavaScript
BasedOnStyle: Google
IndentWidth: 2
JavaScriptQuotes: Single
---
Language: Json
IndentWidth: 2
---
Language: Proto
BasedOnStyle: Google
IndentWidth: 2
---
```
## Tips
1. **Separate Configs**: Use multiple `---` sections for different languages
2. **Shared Base**: Start each language with same `BasedOnStyle` for consistency
3. **Language Detection**: Verify correct language is detected with `--dump-config`
4. **Import Organization**: Configure Java imports and include sorting consistently
5. **Quote Style**: Match JavaScript quotes to your linter/prettier settings
6. **JSON Formatting**: Consider separate JSON formatter for complex configuration files
## See Also
- [Include Organization](06-includes.md) - Organize imports/includes
- [Comments & Misc](08-comments.md) - Comment formatting
- [CLI Usage](cli-usage.md) - Language detection and override
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Includes](06-includes.md) | [Back to Index](index.md) | [Next: Comments →](08-comments.md)

View File

@@ -0,0 +1,705 @@
# Comments & Miscellaneous Options
[← Prev: Languages](07-languages.md) | [Back to Index](index.md) | [Next: Advanced →](09-advanced.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Comment formatting and miscellaneous options.
## Comment Formatting
### ReflowComments
Comment reformatting style.
**Type:** `ReflowCommentsStyle` **Default:** `Always` **Version:** clang-format 3.8
**Values:**
- `Never` - Leave comments untouched
- `Always` - Apply indentation rules and reflow long comments into new lines, trying to obey the ColumnLimit
**Example:**
`Always`:
```cpp
// This is a very long comment that will be automatically
// reflowed to fit within the column limit when enabled
```
`Never`:
```cpp
// This is a very long comment that will not be reflowed even if it exceeds column limit
```
### CommentPragmas
A regular expression that describes comments with special meaning, which should not be split into lines or otherwise changed.
**Type:** `String` **Default:** `^\\s*IWYU pragma:` **Version:** clang-format 3.7
Comments matching this regex will not be reflowed.
**Example:**
```yaml
CommentPragmas: "^ FOOBAR pragma:"
```
```cpp
#include <vector> // FOOBAR pragma: keep
```
### FixNamespaceComments
Add/fix end-of-namespace comments for namespaces and fixes invalid existing ones. This doesn't affect short namespaces, which are controlled by `ShortNamespaceLines`.
**Type:** `Boolean` **Default:** `true` **Version:** clang-format 5
**Example:**
`true`:
```cpp
namespace longNamespace {
void foo();
void bar();
} // namespace longNamespace
namespace shortNamespace {
void baz();
}
```
`false`:
```cpp
namespace longNamespace {
void foo();
void bar();
}
namespace shortNamespace {
void baz();
}
```
### CompactNamespaces
If `true`, consecutive namespace declarations will be on the same line. If `false`, each namespace is declared on a new line.
**Type:** `Boolean` **Default:** `false` **Version:** clang-format 5
**Example:**
`true`:
```cpp
namespace Foo { namespace Bar {
}}
```
`false`:
```cpp
namespace Foo {
namespace Bar {
}
}
```
### ShortNamespaceLines
The maximal number of unwrapped lines that a short namespace spans. Defaults to 1.
**Type:** `Unsigned` **Default:** `1` **Version:** clang-format 13
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.
**Example:**
`ShortNamespaceLines: 1`:
```cpp
namespace a {
int foo;
}
namespace b {
int foo;
int bar;
} // namespace b
```
`ShortNamespaceLines: 0`:
```cpp
namespace a {
int foo;
} // namespace a
namespace b {
int foo;
int bar;
} // namespace b
```
### WrapNamespaceBodyWithEmptyLines
Wrap namespace body with empty lines.
**Type:** `WrapNamespaceBodyWithEmptyLinesStyle` **Version:** clang-format 20
**Values:**
- `Never` - Remove all empty lines at the beginning and the end of namespace body
- `Always` - Always have at least one empty line at the beginning and the end of namespace body except that the number of empty lines between consecutive nested namespace definitions is not increased
- `Leave` - Keep existing newlines at the beginning and the end of namespace body. `MaxEmptyLinesToKeep` still applies
**Example:**
`Never`:
```cpp
namespace N1 {
namespace N2 {
function();
}
}
```
`Always`:
```cpp
namespace N1 {
namespace N2 {
function();
}
}
```
`Leave`:
```cpp
// Keeps existing empty lines as they are
```
## Macros
### AttributeMacros
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.
**Type:** `List of Strings` **Version:** clang-format 12
**Example:**
```yaml
AttributeMacros: [__capability, __output, __unused]
```
```cpp
x = (char *__capability)&y;
int function(void) __unused;
void only_writes_to_buffer(char *__output buffer);
```
### ForEachMacros
A vector of macros that should be interpreted as foreach loops instead of as function calls.
**Type:** `List of Strings` **Version:** clang-format 3.7
These are expected to be macros of the form:
```cpp
FOREACH(<variable-declaration>, ...)
<loop-body>
```
**Example:**
```yaml
ForEachMacros: [RANGES_FOR, FOREACH]
```
For example: BOOST_FOREACH
```cpp
FOREACH(item, list) {
doSomething(item);
}
```
### IfMacros
A vector of macros that should be interpreted as conditionals instead of as function calls.
**Type:** `List of Strings` **Version:** clang-format 13
These are expected to be macros of the form:
```cpp
IF(...)
<conditional-body>
else IF(...)
<conditional-body>
```
**Example:**
```yaml
IfMacros: [IF]
```
For example: KJ_IF_MAYBE
### StatementAttributeLikeMacros
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 Qt's emit.
**Type:** `List of Strings` **Version:** clang-format 12
**Example:**
```yaml
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
A vector of macros that should be interpreted as complete statements.
**Type:** `List of Strings` **Version:** clang-format 8
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.
**Example:**
For example: Q_UNUSED
```yaml
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
```
### TypenameMacros
A vector of macros that should be interpreted as type declarations instead of as function calls.
**Type:** `List of Strings` **Version:** clang-format 9
These are expected to be macros of the form:
```cpp
STACK_OF(...)
```
**Example:**
For example: OpenSSL STACK_OF, BSD LIST_ENTRY
```yaml
TypenameMacros:
- STACK_OF
- LIST
```
### WhitespaceSensitiveMacros
A vector of macros which are whitespace-sensitive and should not be touched.
**Type:** `List of Strings` **Version:** clang-format 11
These are expected to be macros of the form:
```cpp
STRINGIZE(...)
```
**Example:**
For example: BOOST_PP_STRINGIZE
```yaml
WhitespaceSensitiveMacros:
- STRINGIZE
- PP_STRINGIZE
```
## Line Endings and Formatting Control
### LineEnding
Line ending style (`\n` or `\r\n`) to use.
**Type:** `LineEndingStyle` **Version:** clang-format 16
**Values:**
- `LF` - Use `\n` (Unix/Linux/Mac)
- `CRLF` - Use `\r\n` (Windows)
- `DeriveLF` - Use `\n` unless the input has more lines ending in `\r\n`
- `DeriveCRLF` - Use `\r\n` unless the input has more lines ending in `\n`
**Example:**
```yaml
LineEnding: LF # Unix/Linux/Mac
LineEnding: CRLF # Windows
LineEnding: DeriveLF # Auto-detect, prefer LF
```
### DeriveLineEnding
**DEPRECATED** - This option is deprecated. See `DeriveLF` and `DeriveCRLF` of `LineEnding`.
Automatically detect line ending style.
**Type:** `Boolean` **Default:** `true` **Version:** clang-format 10
### UseCRLF
**DEPRECATED** - This option is deprecated. See `LF` and `CRLF` of `LineEnding`.
Use Windows-style line endings (CRLF).
**Type:** `Boolean` **Default:** `false` **Version:** clang-format 10
**Example:**
`true` - Use `\r\n` (Windows) `false` - Use `\n` (Unix/Linux/Mac)
### DisableFormat
Completely disable formatting.
**Type:** `Boolean`
When `true`, clang-format won't modify the file at all.
### InsertNewlineAtEOF
Insert newline at end of file.
**Type:** `Boolean`
Ensures file ends with a newline character.
### KeepFormFeed
Keep form feed characters.
**Type:** `Boolean`
Preserves ASCII form feed characters (\\f) in source.
## Trailing Commas
### InsertTrailingCommas
Automatically insert trailing commas.
**Type:** `TrailingCommaStyle` **Values:**
- `None` - Don't insert trailing commas
- `Wrapped` - Insert trailing commas in wrapped function calls
**Example:**
`Wrapped` (JavaScript):
```javascript
const x = {
a: 1,
b: 2, // trailing comma added
};
```
### EnumTrailingComma
Insert a comma (if missing) or remove the comma at the end of an `enum` enumerator list.
**Type:** `EnumTrailingCommaStyle` **Version:** clang-format 21
**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.
**Values:**
- `Leave` - Don't insert or remove trailing commas
- `Insert` - Insert trailing commas
**Example:**
`Leave`:
```cpp
enum { a, b, c, };
enum Color { red, green, blue };
```
`Insert`:
```cpp
enum { a, b, c, };
enum Color { red, green, blue, };
```
## Integer Literals
### IntegerLiteralSeparator
Configure digit separators in integer literals.
**Type:** `IntegerLiteralSeparatorStyle` **Sub-options:**
- `Binary` - Separator for binary literals (0b)
- `BinaryMinDigits` - Minimum digits for binary
- `Decimal` - Separator for decimal
- `DecimalMinDigits` - Minimum digits for decimal
- `Hex` - Separator for hexadecimal
- `HexMinDigits` - Minimum digits for hex
**Example:**
```yaml
IntegerLiteralSeparator:
Binary: 4
Decimal: 3
Hex: 2
```
```cpp
int a = 100'000'000; // Decimal separator every 3 digits
int b = 0b1010'1010; // Binary separator every 4 digits
int c = 0xDEAD'BEEF; // Hex separator every 2 digits
```
## Empty Lines
### EmptyLineAfterAccessModifier
Add empty line after access modifiers.
**Type:** `EmptyLineAfterAccessModifierStyle` **Values:**
- `Never`, `Leave`, `Always`
**Example:**
`Always`:
```cpp
class Foo {
private:
int x;
public:
void bar();
};
```
### EmptyLineBeforeAccessModifier
Add empty line before access modifiers.
**Type:** `EmptyLineBeforeAccessModifierStyle` **Values:**
- `Never`, `Leave`, `Always`, `LogicalBlock`
**Example:**
`Always`:
```cpp
class Foo {
int x;
private:
int y;
public:
void bar();
};
```
## Pointer and Reference Alignment
### PointerAlignment
Alignment of pointers and references.
**Type:** `PointerAlignmentStyle` **Values:**
- `Left` - Align to left
- `Right` - Align to right
- `Middle` - Align to middle
**Examples:**
`Left`:
```cpp
int* a;
int& b;
```
`Right`:
```cpp
int *a;
int &b;
```
`Middle`:
```cpp
int * a;
int & b;
```
### DerivePointerAlignment
Derive pointer alignment from existing code.
**Type:** `Boolean`
When `true`, overrides `PointerAlignment` based on majority style in file.
### ReferenceAlignment
Separate alignment for references (overrides PointerAlignment for references).
**Type:** `ReferenceAlignmentStyle` **Values:**
- `Pointer` - Same as pointers
- `Left`, `Right`, `Middle`
## Qualifier Alignment
### QualifierAlignment
Position of const/volatile qualifiers.
**Type:** `QualifierAlignmentStyle` **Values:**
- `Leave` - Don't change
- `Left` - const int
- `Right` - int const
- `Custom` - Use QualifierOrder
**Example:**
`Left`:
```cpp
const int a;
const int* b;
```
`Right`:
```cpp
int const a;
int const* b;
```
### QualifierOrder
Custom qualifier order when `QualifierAlignment: Custom`.
**Type:** `List of Strings`
**Example:**
```yaml
QualifierAlignment: Custom
QualifierOrder:
- inline
- static
- constexpr
- const
- volatile
- type
```
## Common Patterns
### Namespace and Comment Handling
```yaml
FixNamespaceComments: true
CompactNamespaces: false
ReflowComments: true
CommentPragmas: "^ IWYU pragma:|^ NOLINT"
```
### Line Endings
Modern (v16+):
```yaml
LineEnding: DeriveLF # Auto-detect, prefer Unix
InsertNewlineAtEOF: true
```
Legacy (deprecated):
```yaml
DeriveLineEnding: true # DEPRECATED - use LineEnding: DeriveLF
UseCRLF: false # DEPRECATED - use LineEnding: LF
InsertNewlineAtEOF: true
```
### Pointer Style (Left-Aligned)
```yaml
PointerAlignment: Left
ReferenceAlignment: Left
DerivePointerAlignment: false
```
### Pointer Style (Right-Aligned)
```yaml
PointerAlignment: Right
ReferenceAlignment: Right
DerivePointerAlignment: false
```
## Tips
1. **Comment Reflow**: Disable `ReflowComments` if you have carefully formatted comments
2. **Namespace Comments**: `FixNamespaceComments` helps navigate large codebases
3. **Namespace Empty Lines**: Use `WrapNamespaceBodyWithEmptyLines` (v20+) to control empty lines in namespace bodies
4. **Macro Lists**: Maintain accurate macro lists for correct formatting
5. **Pointer Alignment**: Choose one style and enforce it with `DerivePointerAlignment: false`
6. **Line Endings**: Use `LineEnding: DeriveLF` (v16+) for mixed-platform teams. Replaces deprecated `DeriveLineEnding` and `UseCRLF`
7. **Trailing Commas**: Useful in JavaScript/TypeScript for cleaner diffs
8. **Enum Trailing Commas**: Use `EnumTrailingComma` (v21+) carefully, as it may cause formatting issues
9. **Integer Separators**: Improves readability of large numeric literals
## See Also
- [Spacing](05-spacing.md) - Control whitespace
- [Languages](07-languages.md) - Language-specific options
- [Advanced](09-advanced.md) - Experimental features
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Languages](07-languages.md) | [Back to Index](index.md) | [Next: Advanced →](09-advanced.md)

View File

@@ -0,0 +1,557 @@
# Advanced & Experimental Options
[← Prev: Comments](08-comments.md) | [Back to Index](index.md) | [Quick Reference](quick-reference.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Experimental, advanced, and less commonly used options.
## Experimental Options
### ExperimentalAutoDetectBinPacking
Automatically detect bin packing from existing code.
**Type:** `Boolean` **Default:** `false` **Status:** Experimental
When enabled, clang-format attempts to detect whether arguments/parameters are bin-packed in the existing code and maintains that style.
**Warning:** This is experimental and may not work perfectly.
## C++ Specific
### Cpp11BracedListStyle
Use C++11 braced list style.
**Type:** `BracedListStyle` **Default:** `true`
**Example:**
`true`:
```cpp
vector<int> x{1, 2, 3, 4};
vector<T> x{{}, {}, {}, {}};
f(MyMap[{composite, key}]);
new int[3]{1, 2, 3};
```
`false`:
```cpp
vector<int> x{ 1, 2, 3, 4 };
vector<T> x{ {}, {}, {}, {} };
f(MyMap[{ composite, key }]);
new int[3]{ 1, 2, 3 };
```
### AlwaysBreakTemplateDeclarations
Control breaking after template declarations (deprecated).
**Type:** `BreakTemplateDeclarationsStyle` **Note:** Use `BreakTemplateDeclarations` instead
### AlwaysBreakAfterDefinitionReturnType
Control breaking after function definition return type (deprecated).
**Type:** `DefinitionReturnTypeBreakingStyle` **Note:** Use `BreakAfterReturnType` instead
### AllowAllConstructorInitializersOnNextLine
Allow constructor initializers on next line (deprecated).
**Type:** `Boolean` **Default:** `true` **Note:** Deprecated in favor of `PackConstructorInitializers`
### ConstructorInitializerAllOnOneLineOrOnePerLine
Format constructor initializers (deprecated).
**Type:** `Boolean` **Note:** Deprecated in favor of `PackConstructorInitializers`
### PackConstructorInitializers
How to pack constructor initializers.
**Type:** `PackConstructorInitializersStyle` **Values:**
- `Never` - Always put one per line
- `BinPack` - Bin-pack constructor initializers
- `CurrentLine` - Pack on current line if it fits
- `NextLine` - Pack on next line
## BinPacking
### BinPackLongBracedList
Bin-pack long braced lists.
**Type:** `Boolean`
When true, long braced lists will be bin-packed even if arguments aren't.
## Breaking Binary Operations
### BreakBinaryOperations
Control breaking of binary operations.
**Type:** `BreakBinaryOperationsStyle` **Values:**
- `RespectPrecedence` - Break respecting precedence
- `OnePerLine` - One operation per line
- `Never` - Don't break
**Example:**
`OnePerLine`:
```cpp
auto x =
(aaaaa
+ bbbbb
+ ccccc);
```
## Template Behavior
### BreakBeforeTemplateCloser
Break before `>` in template declarations.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
template<typename T
>
class Foo {};
```
`false`:
```cpp
template<typename T>
class Foo {};
```
### AlwaysBreakBeforeMultilineStrings
Always break before multiline string literals.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
aaaa =
"bbbb"
"cccc";
```
`false`:
```cpp
aaaa = "bbbb"
"cccc";
```
## Special Case Handling
### AllowShortCaseExpressionOnASingleLine
Allow short case expressions on one line (for pattern matching languages).
**Type:** `Boolean`
### AllowShortCompoundRequirementOnASingleLine
Allow short compound requirements on one line (C++20 concepts).
**Type:** `Boolean`
### AllowShortNamespacesOnASingleLine
Allow short namespace declarations on one line.
**Type:** `Boolean`
**Example:**
`true`:
```cpp
namespace a { class A; }
```
`false`:
```cpp
namespace a {
class A;
}
```
### AllowBreakBeforeNoexceptSpecifier
Control breaking before noexcept specifier.
**Type:** `BreakBeforeNoexceptSpecifierStyle` **Values:**
- `Never`, `OnlyWithParen`, `Always`
### AllowBreakBeforeQtProperty
Allow breaking before Qt property keywords.
**Type:** `Boolean` **Since:** v22
Allow breaking before `Q_Property` keywords `READ`, `WRITE`, etc. as if they were preceded by a comma. This allows them to be formatted according to `BinPackParameters`.
**Example:**
When enabled with appropriate bin-packing settings, Qt property declarations can have their keywords broken across lines more flexibly.
## Numeric Literals
### NumericLiteralCase
Capitalization style for numeric literals.
**Type:** `NumericLiteralCaseStyle` **Since:** v22
Separate control for each numeric literal component.
**Sub-options:**
- `ExponentLetter` - Format floating point exponent separator letter case
- `HexDigit` - Format hexadecimal digit case
- `Prefix` - Format integer prefix case
- `Suffix` - Format suffix case (excludes case-sensitive reserved suffixes like `min` in C++)
**Values for each component:**
- `Leave` - Leave this component as is
- `Upper` - Format with uppercase characters
- `Lower` - Format with lowercase characters
**Example:**
```yaml
NumericLiteralCase:
ExponentLetter: Leave
HexDigit: Lower
Prefix: Upper
Suffix: Lower
```
**Before:**
```cpp
float a = 6.02e23 + 1.0E10;
a = 0xaBcDeF;
a = 0xF0 | 0b1;
a = 1uLL;
```
**After (with config above):**
```cpp
float a = 6.02e23 + 1.0E10; // ExponentLetter: Leave
a = 0xabcdef; // HexDigit: Lower
a = 0XF0 | 0B1; // Prefix: Upper
a = 1ull; // Suffix: Lower
```
## Spacing in Empty Constructs
### SpaceInEmptyBraces
Specifies when to insert a space in empty braces.
**Type:** `SpaceInEmptyBracesStyle` **Since:** v22 **Note:** Replaces deprecated `SpaceInEmptyBlock` option
**Values:**
- `Always` - Always insert a space in empty braces
- `Block` - Only insert a space in empty blocks (functions, classes, lambdas)
- `Never` - Never insert a space in empty braces
**Example:**
`Always`:
```cpp
void f() { }
class Unit { };
auto a = [] { };
int x{ };
```
`Block`:
```cpp
void f() { }
class Unit { };
auto a = [] { };
int x{}; // No space in initializer braces
```
`Never`:
```cpp
void f() {}
class Unit {};
auto a = [] {};
int x{};
```
**Note:** This option does not apply to initializer braces if `Cpp11BracedListStyle` is not `Block`.
## Penalty System
These options control clang-format's internal penalty system for choosing formatting. Higher values make clang-format less likely to choose that formatting.
### PenaltyBreakAssignment
Penalty for breaking around assignment operator.
**Type:** `Unsigned`
### PenaltyBreakBeforeFirstCallParameter
Penalty for breaking before first call parameter.
**Type:** `Unsigned`
### PenaltyBreakBeforeMemberAccess
Penalty for breaking before a member access operator (`.` or `->`).
**Type:** `Unsigned` **Since:** v20
Controls how reluctant clang-format is to break before member access operators. Higher values make it less likely to break.
**Example:**
With lower penalty:
```cpp
object
->member
->anotherMember();
```
With higher penalty:
```cpp
object->member->anotherMember();
```
### PenaltyBreakComment
Penalty for breaking inside comment.
**Type:** `Unsigned`
### PenaltyBreakFirstLessLess
Penalty for breaking before first `<<`.
**Type:** `Unsigned`
### PenaltyBreakOpenParenthesis
Penalty for breaking after open parenthesis.
**Type:** `Unsigned`
### PenaltyBreakScopeResolution
Penalty for breaking after scope resolution operator (`::`).
**Type:** `Unsigned` **Since:** v18
Controls how reluctant clang-format is to break after `::` in qualified names. Higher values make it less likely to break.
**Example:**
With lower penalty:
```cpp
namespace::
ClassName::
memberFunction();
```
With higher penalty:
```cpp
namespace::ClassName::memberFunction();
```
### PenaltyBreakString
Penalty for breaking string literals.
**Type:** `Unsigned`
### PenaltyBreakTemplateDeclaration
Penalty for breaking after template declaration.
**Type:** `Unsigned`
### PenaltyExcessCharacter
Penalty for each character outside column limit.
**Type:** `Unsigned`
### PenaltyIndentedWhitespace
Penalty for indented whitespace.
**Type:** `Unsigned`
### PenaltyReturnTypeOnItsOwnLine
Penalty for putting return type on its own line.
**Type:** `Unsigned`
### ShortNamespaceLines
Maximum lines for considering namespace short.
**Type:** `Unsigned`
## Raw String Formatting
### RawStringFormats
Configure formatting of raw string literals.
**Type:** `List of RawStringFormat`
**Example:**
```yaml
RawStringFormats:
- Language: TextProto
Delimiters:
- pb
- proto
EnclosingFunctions:
- PARSE_TEXT_PROTO
BasedOnStyle: Google
```
This allows formatting embedded protocol buffer text within raw strings.
## Namespace Handling
### NamespaceIndentation
Indent content in namespaces.
**Type:** `NamespaceIndentationKind` **Values:**
- `None` - Don't indent
- `Inner` - Indent inner namespaces only
- `All` - Indent all namespaces
**Example:**
`None`:
```cpp
namespace out {
namespace in {
class foo {};
}
}
```
`Inner`:
```cpp
namespace out {
namespace in {
class foo {};
}
}
```
`All`:
```cpp
namespace out {
namespace in {
class foo {};
}
}
```
### NamespaceMacros
Macros that behave like namespace declarations.
**Type:** `List of Strings`
## Fine-Tuning
### PPIndentWidth
Indentation width for preprocessor statements.
**Type:** `Integer` **Default:** Uses `IndentWidth`
Separate from `IndentPPDirectives`, this controls the width when indenting.
## When to Use Advanced Options
1. **Penalties**: Only adjust if default formatting doesn't match preferences
2. **Experimental Features**: Use with caution in production code
3. **Deprecated Options**: Migrate to newer equivalents
4. **Special Cases**: Handle edge cases in complex codebases
## Tips
1. **Start Simple**: Begin with predefined styles and common options
2. **Test Thoroughly**: Advanced options can have unexpected interactions
3. **Document Choices**: Explain why specific advanced options are used
4. **Monitor Changes**: Watch for behavioral changes in new clang-format versions
5. **Penalty Tuning**: Only adjust penalties as a last resort after trying other options
## Debugging Formatting
To understand why clang-format makes certain choices:
```bash
# See effective configuration
clang-format --dump-config file.cpp
# Verbose output (if available in your version)
clang-format --verbose file.cpp
# Check specific formatting
clang-format --style="{BasedOnStyle: llvm, ColumnLimit: 100}" --dry-run file.cpp
```
## See Also
- [Breaking & Line Wrapping](02-breaking.md) - Core breaking options
- [Comments & Misc](08-comments.md) - Common miscellaneous options
- [Quick Reference](quick-reference.md) - Complete working examples
- [Full Style Options Reference](complete/clang-format-style-options.md)
---
[← Prev: Comments](08-comments.md) | [Back to Index](index.md) | [Quick Reference](quick-reference.md)

View File

@@ -0,0 +1,541 @@
# clang-format CLI Usage
[← Back to Index](index.md) | [Quick Reference](quick-reference.md) | [Full CLI Reference](complete/clang-format-cli.md)
Command-line usage, tools, and integrations for clang-format.
**Documentation Version:** Updated for Clang v22.0.0
## Command-Line Options
### Basic Usage
```bash
# Format from stdin, output to stdout
cat file.cpp | clang-format
# Format file(s) and output to stdout
clang-format file.cpp
# Format file(s) in-place
clang-format -i file.cpp file.h
# Format multiple files
clang-format -i src/*.cpp include/*.h
```
### Common Flags
#### `-i` - In-Place Editing
Modify files directly instead of outputting to stdout:
```bash
clang-format -i file.cpp
```
#### `--style=<style>` - Set Coding Style
Specify the formatting style:
```bash
# Use a predefined style
clang-format --style=google file.cpp
# Use .clang-format file (default)
clang-format --style=file file.cpp
# Specify explicit config file path
clang-format --style=file:/path/to/.clang-format file.cpp
# Inline style configuration
clang-format --style="{BasedOnStyle: llvm, IndentWidth: 8}" file.cpp
```
**Available Predefined Styles:**
- `LLVM`, `GNU`, `Google`, `Chromium`, `Microsoft`, `Mozilla`, `WebKit`, `InheritParentConfig`
Note: `InheritParentConfig` is not a real style, but allows using the `.clang-format` file from the parent directory. If no parent file is found, it falls back to the `fallback` style.
#### `--dry-run` / `-n` - Check Without Modifying
Check what would change without making modifications:
```bash
clang-format --dry-run file.cpp
clang-format -n file.cpp
```
#### `--fallback-style=<style>` - Fallback Style
Style to use if `.clang-format` file cannot be found:
```bash
clang-format --style=file --fallback-style=google file.cpp
# Skip formatting if no config found
clang-format --style=file --fallback-style=none file.cpp
```
#### `--dump-config` - Show Effective Configuration
Display the configuration that will be used:
```bash
# Dump LLVM style
clang-format --style=llvm --dump-config
# Dump effective config for a file
clang-format --dump-config file.cpp
# Create .clang-format from a style
clang-format --style=google --dump-config > .clang-format
```
### Advanced Options
#### `--lines=<start>:<end>` - Format Specific Lines
Format only specified line ranges:
```bash
# Format lines 10-20
clang-format --lines=10:20 file.cpp
# Format multiple ranges
clang-format --lines=10:20 --lines=50:60 file.cpp
```
#### `--offset=<bytes>` and `--length=<bytes>` - Format by Byte Range
Format specific byte ranges:
```bash
clang-format --offset=100 --length=500 file.cpp
# Format from offset to end of file
clang-format --offset=100 file.cpp
```
#### `--assume-filename=<name>` - Set Language for stdin
Specify filename for language detection when reading from stdin:
```bash
cat source.txt | clang-format --assume-filename=file.cpp
```
**Supported Languages (as of Clang v22):**
- C
- C++ (Cpp)
- C# (CSharp): `.cs`
- Java: `.java`
- JavaScript: `.js`, `.mjs`, `.cjs`, `.ts`
- JSON (Json): `.json`, `.ipynb`
- Objective-C (ObjC): `.m`, `.mm`
- Protocol Buffers (Proto): `.proto`, `.protodevel`
- TableGen: `.td`
- Text Protocol Buffers (TextProto): `.txtpb`, `.textpb`, `.pb.txt`, `.textproto`, `.asciipb`
- Verilog: `.sv`, `.svh`, `.v`, `.vh`
For `.h` files, you can specify the language by adding `// clang-format Language: Cpp` (or `C`, `ObjC`) before the first non-comment line.
#### `--files=<filename>` - Process File List
Read list of files to process from a file:
```bash
# Create file list
find src -name '*.cpp' > files.txt
# Format all files in list
clang-format -i --files=files.txt
```
#### `--verbose` - Show Processed Files
Display the list of files being processed:
```bash
clang-format -i --verbose src/*.cpp
```
### Error Handling
#### `--Werror` - Treat Warnings as Errors
Convert formatting warnings to errors:
```bash
clang-format --Werror --dry-run file.cpp
```
#### `--Wno-error=<type>` - Ignore Specific Warnings
```bash
# Allow unknown format options
clang-format --Wno-error=unknown -i file.cpp
```
#### `--ferror-limit=<n>` - Limit Error Count
Set maximum number of errors before stopping:
```bash
clang-format --dry-run --ferror-limit=10 file.cpp
```
#### `--fail-on-incomplete-format` - Fail on Incomplete Formatting
Exit with code 1 if formatting is incomplete:
```bash
clang-format --fail-on-incomplete-format file.cpp
```
## .clang-format-ignore File
Create a `.clang-format-ignore` file to exclude files from formatting.
### Format
```gitignore
# Comments start with #
# Blank lines are ignored
# Ignore third-party code
third_party/**
external/**
# Ignore generated files
*.pb.cc
*.pb.h
*_generated.cpp
# Ignore specific directories
build/**
node_modules/**
# Negate patterns with !
# Format everything except test data
tests/**
!tests/data/**
# Ignore specific files
legacy/old_code.cpp
vendor/library.h
```
### Pattern Rules
- **Blank lines** are skipped
- **Leading/trailing spaces** are trimmed
- **`#` prefix** indicates a comment
- **`/` separator** for directories
- **Patterns are relative** to the `.clang-format-ignore` file location
- **Absolute patterns** start with `/`
- **Bash globstar `**`\*\* is supported
- **`!` prefix** negates the pattern
### Multiple .clang-format-ignore Files
Similar to `.clang-format` files, you can have multiple `.clang-format-ignore` files at different directory levels. Lower-level files override higher-level ones.
## Git Integration
### git clang-format Command
Format only the lines that have changed in git commits:
```bash
# Format staged changes
git clang-format
# Format everything since HEAD~1
git clang-format HEAD~1
# Format everything since main branch
git clang-format main
# Show diff instead of applying
git clang-format --diff
# Show diffstat
git clang-format --diffstat
# Format specific files only
git clang-format main -- src/*.cpp
# Interactive hunk selection
git clang-format -p
```
### Options
```bash
git clang-format [OPTIONS] [<commit>] [<commit>|--staged] [--] [<file>...]
```
**Common Options:**
- `--binary <path>` - Path to clang-format binary
- `--style <style>` - Formatting style to use
- `--diff` - Print diff instead of applying
- `--diffstat` - Print diffstat instead of applying
- `-f, --force` - Allow changes to unstaged files
- `-p, --patch` - Select hunks interactively
- `--staged, --cached` - Format lines in stage instead of working dir
- `-q, --quiet` - Print less information
- `-v, --verbose` - Print extra information
### Git Config
Configure default options in git config:
```bash
git config clangFormat.binary /usr/local/bin/clang-format
git config clangFormat.style file
git config clangFormat.extensions "h,cpp,cc,c"
```
### Pre-Commit Hook Example
Create `.git/hooks/pre-commit`:
```bash
#!/bin/bash
# Format staged changes before commit
git clang-format --staged --quiet
```
## Script Tools
### clang-format-diff.py
Format only changed lines from a unified diff:
```bash
# Format git diff
git diff -U0 --no-color --relative HEAD^ | clang-format-diff.py -p1 -i
# Format svn diff
svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
# Format mercurial diff
hg diff -U0 --color=never | clang-format-diff.py -i -p1
```
**Options:**
- `-i` - Apply edits to files instead of displaying diff
- `-p <num>` - Strip N leading directories from paths
- `-regex <pattern>` - Custom pattern for file paths (case sensitive)
- `-iregex <pattern>` - Custom pattern for file paths (case insensitive)
- `-style <style>` - Formatting style
- `-fallback-style <style>` - Fallback style
- `-binary <path>` - Path to clang-format binary
- `-v, --verbose` - Be more verbose
**Example with filters:**
```bash
# Only format .cpp files
git diff -U0 | clang-format-diff.py -i -regex '.*\.cpp'
# Format C++ and header files
git diff -U0 | clang-format-diff.py -i -iregex '.*\.(cpp|h)'
```
## Editor Integration
### Visual Studio Code
Install the "Clang-Format" extension from the marketplace.
**Configuration (settings.json):**
```json
{
"editor.defaultFormatter": "xaver.clang-format",
"editor.formatOnSave": true,
"[cpp]": {
"editor.defaultFormatter": "xaver.clang-format"
},
"clang-format.executable": "/usr/bin/clang-format",
"clang-format.style": "file"
}
```
**Default Keybinding:** `Alt+Shift+F`
### CLion
CLion has built-in clang-format support.
**Enable:**
1. Settings → Editor → Code Style
2. Enable "Enable ClangFormat support"
3. Place `.clang-format` in project root
**Features:**
- Automatic formatting on type
- Respects `.clang-format` file
- Can generate `.clang-format` from IDE settings
### Vim
Add to `.vimrc`:
```vim
" Python 3 support
if has('python3')
map <C-K> :py3f /path/to/clang-format.py<cr>
imap <C-K> <c-o>:py3f /path/to/clang-format.py<cr>
endif
" Python 2 support
if has('python')
map <C-K> :pyf /path/to/clang-format.py<cr>
imap <C-K> <c-o>:pyf /path/to/clang-format.py<cr>
endif
```
**Format on save:**
```vim
function! Formatonsave()
let l:formatdiff = 1
py3f /path/to/clang-format.py
endfunction
autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave()
```
### Emacs
Add to `.emacs`:
```elisp
(load "/path/to/clang-format.el")
(global-set-key [C-M-tab] 'clang-format-region)
```
### BBEdit
1. Copy `clang-format-bbedit.applescript` to `~/Library/Application Support/BBEdit/Scripts/`
2. Edit the script to point to your clang-format binary
3. Access from Script menu or assign keyboard shortcut
### Visual Studio
Download the extension from the [LLVM builds site](https://llvm.org/builds/).
**Default Keybinding:** `Ctrl+R, Ctrl+F`
## Common Workflows
### Format Entire Project
```bash
# Find and format all C++ files
find . -name '*.cpp' -o -name '*.h' | xargs clang-format -i
# Using git to find tracked files
git ls-files '*.cpp' '*.h' | xargs clang-format -i
```
### Check Formatting in CI
```bash
# Check if any files need formatting (exit non-zero if changes needed)
clang-format --dry-run --Werror src/**/*.{cpp,h}
# Generate diff for review
clang-format --dry-run src/**/*.{cpp,h} > format-diff.txt
```
### Format Only Modified Files
```bash
# Format files modified in last commit
git diff --name-only HEAD~1 | grep -E '\.(cpp|h)$' | xargs clang-format -i
# Format uncommitted changes
git diff --name-only | grep -E '\.(cpp|h)$' | xargs clang-format -i
```
### Parallel Formatting
```bash
# Format files in parallel (requires GNU parallel)
find src -name '*.cpp' | parallel clang-format -i {}
```
## Troubleshooting
### Configuration File Not Found
clang-format searches for `.clang-format` or `_clang-format` starting from the source file's directory up to the filesystem root.
**Solutions:**
```bash
# Specify config file explicitly
clang-format -style=file:/path/to/.clang-format file.cpp
# Check which config file will be used
clang-format -dump-config file.cpp
```
### Unknown Format Options
Occurs when your config file has options not supported by your clang-format version.
**Solutions:**
```bash
# Warn instead of error
clang-format --Wno-error=unknown -i file.cpp
# Check your clang-format version
clang-format --version
# Regenerate config with your version
clang-format -style=llvm -dump-config > .clang-format
```
### Performance Issues
For large files or projects:
```bash
# Format specific line ranges only
clang-format --lines=100:200 large_file.cpp
# Use parallel processing
find src -name '*.cpp' | parallel -j8 clang-format -i {}
# Format only changed lines
git clang-format
```
## What's New in Clang v22
Clang-format v22 introduces several new style configuration options:
- **AllowBreakBeforeQtProperty**: Control line breaks before Qt `Q_Property` keywords
- **NumericLiteralCase**: Configure capitalization style for numeric literals
- **SpaceInEmptyBraces**: More granular control over spacing in empty braces
For a complete list of v22 style options, refer to the [ClangFormatStyleOptions_v22.md](../../knowledge/ClangFormatStyleOptions_v22.md) documentation.
## Reference
For complete command-line documentation, see [Full CLI Reference](complete/clang-format-cli.md).
---
[← Back to Index](index.md) | [Quick Reference](quick-reference.md) | [Full CLI Reference](complete/clang-format-cli.md)

View File

@@ -0,0 +1,317 @@
# [Clang 22.0.0git documentation](https://clang.llvm.org/docs/index.html)
## ClangFormat
« [ClangCheck](https://clang.llvm.org/docs/ClangCheck.html) :: [Contents](https://clang.llvm.org/docs/index.html) :: [Clang-Format Style Options](https://clang.llvm.org/docs/ClangFormatStyleOptions.html) »
# ClangFormat [¶](https://clang.llvm.org/docs/ClangFormat.html#clangformat "Link to this heading")
ClangFormat describes a set of tools that are built on top of [LibFormat](https://clang.llvm.org/docs/LibFormat.html). It can support your workflow in a variety of ways including a standalone tool and editor integrations.
## Standalone Tool [¶](https://clang.llvm.org/docs/ClangFormat.html#standalone-tool "Link to this heading")
**clang-format** is located in clang/tools/clang-format and can be used to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.
```text
$ clang-format --help
OVERVIEW: A tool to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.
If no arguments are specified, it formats the code from standard input
and writes the result to the standard output.
If <file>s are given, it reformats the files. If -i is specified
together with <file>s, the files are edited in-place. Otherwise, the
result is written to the standard output.
USAGE: clang-format [options] [@<file>] [<file> ...]
OPTIONS:
Clang-format options:
--Werror - If set, changes formatting warnings to errors
--Wno-error=<value> - If set, don't error out on the specified warning type.
=unknown - If set, unknown format options are only warned about.
This can be used to enable formatting, even if the
configuration contains unknown (newer) options.
Use with caution, as this might lead to dramatically
differing format depending on an option being
supported or not.
--assume-filename=<string> - Set filename used to determine the language and to find
.clang-format file.
Only used when reading from stdin.
If this is not passed, the .clang-format file is searched
relative to the current working directory when reading stdin.
Unrecognized filenames are treated as C++.
supported:
CSharp: .cs
Java: .java
JavaScript: .js .mjs .cjs .ts
Json: .json .ipynb
Objective-C: .m .mm
Proto: .proto .protodevel
TableGen: .td
TextProto: .txtpb .textpb .pb.txt .textproto .asciipb
Verilog: .sv .svh .v .vh
--cursor=<uint> - The position of the cursor when invoking
clang-format from an editor integration
--dry-run - If set, do not actually make the formatting changes
--dump-config - Dump configuration options to stdout and exit.
Can be used with -style option.
--fail-on-incomplete-format - If set, fail with exit code 1 on incomplete format.
--fallback-style=<string> - The name of the predefined style used as a
fallback in case clang-format is invoked with
-style=file, but can not find the .clang-format
file to use. Defaults to 'LLVM'.
Use -fallback-style=none to skip formatting.
--ferror-limit=<uint> - Set the maximum number of clang-format errors to emit
before stopping (0 = no limit).
Used only with --dry-run or -n
--files=<filename> - A file containing a list of files to process, one per line.
-i - Inplace edit <file>s, if specified.
--length=<uint> - Format a range of this length (in bytes).
Multiple ranges can be formatted by specifying
several -offset and -length pairs.
When only a single -offset is specified without
-length, clang-format will format up to the end
of the file.
Can only be used with one input file.
--lines=<string> - <start line>:<end line> - format a range of
lines (both 1-based).
Multiple ranges can be formatted by specifying
several -lines arguments.
Can't be used with -offset and -length.
Can only be used with one input file.
-n - Alias for --dry-run
--offset=<uint> - Format a range starting at this byte offset.
Multiple ranges can be formatted by specifying
several -offset and -length pairs.
Can only be used with one input file.
--output-replacements-xml - Output replacements as XML.
--qualifier-alignment=<string> - If set, overrides the qualifier alignment style
determined by the QualifierAlignment style flag
--sort-includes - If set, overrides the include sorting behavior
determined by the SortIncludes style flag
--style=<string> - Set coding style. <string> can be:
1. A preset: LLVM, GNU, Google, Chromium, Microsoft,
Mozilla, WebKit.
2. 'file' to load style configuration from a
.clang-format file in one of the parent directories
of the source file (for stdin, see --assume-filename).
If no .clang-format file is found, falls back to
--fallback-style.
--style=file is the default.
3. 'file:<format_file_path>' to explicitly specify
the configuration file.
4. "{key: value, ...}" to set specific parameters, e.g.:
--style="{BasedOnStyle: llvm, IndentWidth: 8}"
--verbose - If set, shows the list of processed files
Generic Options:
--help - Display available options (--help-hidden for more)
--help-list - Display list of available options (--help-list-hidden for more)
--version - Display the version of this program
```
When the desired code formatting style is different from the available options, the style can be customized using the `-style="{key: value, ...}"` option or by putting your style configuration in the `.clang-format` or `_clang-format` file in your projects directory and using `clang-format -style=file`.
An easy way to create the `.clang-format` file is:
```bash
clang-format -style=llvm -dump-config > .clang-format
```
Available style options are described in [Clang-Format Style Options](https://clang.llvm.org/docs/ClangFormatStyleOptions.html).
## .clang-format-ignore [¶](https://clang.llvm.org/docs/ClangFormat.html#clang-format-ignore "Link to this heading")
You can create `.clang-format-ignore` files to make `clang-format` ignore certain files. A `.clang-format-ignore` file consists of patterns of file path names. It has the following format:
- A blank line is skipped.
- Leading and trailing spaces of a line are trimmed.
- A line starting with a hash ( `#`) is a comment.
- A non-comment line is a single pattern.
- The slash ( `/`) is used as the directory separator.
- A pattern is relative to the directory of the `.clang-format-ignore` file (or the root directory if the pattern starts with a slash). Patterns containing drive names (e.g. `C:`) are not supported.
- Patterns follow the rules specified in [POSIX 2.13.1, 2.13.2, and Rule 1 of\\ 2.13.3](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13).
- Bash globstar ( `**`) is supported.
- A pattern is negated if it starts with a bang ( `!`).
To match all files in a directory, use e.g. `foo/bar/*`. To match all files in the directory of the `.clang-format-ignore` file, use `*`. Multiple `.clang-format-ignore` files are supported similar to the `.clang-format` files, with a lower directory level file voiding the higher level ones.
## Vim Integration [¶](https://clang.llvm.org/docs/ClangFormat.html#vim-integration "Link to this heading")
There is an integration for **vim** which lets you run the **clang-format** standalone tool on your current buffer, optionally selecting regions to reformat. The integration has the form of a python-file which can be found under clang/tools/clang-format/clang-format.py.
This can be integrated by adding the following to your .vimrc:
```vim
if has('python')
map <C-K> :pyf <path-to-this-file>/clang-format.py<cr>
imap <C-K> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
elseif has('python3')
map <C-K> :py3f <path-to-this-file>/clang-format.py<cr>
imap <C-K> <c-o>:py3f <path-to-this-file>/clang-format.py<cr>
endif
```
The first line enables **clang-format** for NORMAL and VISUAL mode, the second line adds support for INSERT mode. Change “C-K” to another binding if you need **clang-format** on a different key (C-K stands for Ctrl+k).
With this integration you can press the bound key and clang-format will format the current line in NORMAL and INSERT mode or the selected region in VISUAL mode. The line or region is extended to the next bigger syntactic entity.
It operates on the current, potentially unsaved buffer and does not create or save any files. To revert a formatting, just undo.
An alternative option is to format changes when saving a file and thus to have a zero-effort integration into the coding workflow. To do this, add this to your .vimrc:
```vim
function! Formatonsave()
let l:formatdiff = 1
pyf <path-to-this-file>/clang-format.py
endfunction
autocmd BufWritePre *.h,*.cc,*.cpp call Formatonsave()
```
## Emacs Integration [¶](https://clang.llvm.org/docs/ClangFormat.html#emacs-integration "Link to this heading")
Similar to the integration for **vim**, there is an integration for **emacs**. It can be found at clang/tools/clang-format/clang-format.el and used by adding this to your .emacs:
```lisp
(load "<path-to-clang>/tools/clang-format/clang-format.el")
(global-set-key [C-M-tab] 'clang-format-region)
```
This binds the function clang-format-region to C-M-tab, which then formats the current line or selected region.
## BBEdit Integration [¶](https://clang.llvm.org/docs/ClangFormat.html#bbedit-integration "Link to this heading")
**clang-format** cannot be used as a text filter with BBEdit, but works well via a script. The AppleScript to do this integration can be found at clang/tools/clang-format/clang-format-bbedit.applescript; place a copy in ~/Library/Application Support/BBEdit/Scripts, and edit the path within it to point to your local copy of **clang-format**.
With this integration you can select the script from the Script menu and **clang-format** will format the selection. Note that you can rename the menu item by renaming the script, and can assign the menu item a keyboard shortcut in the BBEdit preferences, under Menus & Shortcuts.
## CLion Integration [¶](https://clang.llvm.org/docs/ClangFormat.html#clion-integration "Link to this heading")
**clang-format** is integrated into [CLion](https://www.jetbrains.com/clion/) as an alternative code formatter. CLion turns it on automatically when there is a `.clang-format` file under the project root. Code style rules are applied as you type, including indentation, auto-completion, code generation, and refactorings.
**clang-format** can also be enabled without a `.clang-format` file. In this case, CLion prompts you to create one based on the current IDE settings or the default LLVM style.
## Visual Studio Integration [¶](https://clang.llvm.org/docs/ClangFormat.html#visual-studio-integration "Link to this heading")
Download the latest Visual Studio extension from the [alpha build site](https://llvm.org/builds/). The default key-binding is Ctrl-R,Ctrl-F.
## Visual Studio Code Integration [¶](https://clang.llvm.org/docs/ClangFormat.html#visual-studio-code-integration "Link to this heading")
Get the latest Visual Studio Code extension from the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=xaver.clang-format). The default key-binding is Alt-Shift-F.
## Git integration [¶](https://clang.llvm.org/docs/ClangFormat.html#git-integration "Link to this heading")
The script clang/tools/clang-format/git-clang-format can be used to format just the lines touched in git commits:
```text
% git clang-format -h
usage: git clang-format [OPTIONS] [<commit>] [<commit>|--staged] [--] [<file>...]
If zero or one commits are given, run clang-format on all lines that differ
between the working directory and <commit>, which defaults to HEAD. Changes are
only applied to the working directory, or in the stage/index.
Examples:
To format staged changes, i.e everything that's been `git add`ed:
git clang-format
To also format everything touched in the most recent commit:
git clang-format HEAD~1
If you're on a branch off main, to format everything touched on your branch:
git clang-format main
If two commits are given (requires --diff), run clang-format on all lines in the
second <commit> that differ from the first <commit>.
The following git-config settings set the default of the corresponding option:
clangFormat.binary
clangFormat.commit
clangFormat.extensions
clangFormat.style
positional arguments:
<commit> revision from which to compute the diff
<file>... if specified, only consider differences in these files
optional arguments:
-h, --help show this help message and exit
--binary BINARY path to clang-format
--commit COMMIT default commit to use if none is specified
--diff print a diff instead of applying the changes
--diffstat print a diffstat instead of applying the changes
--extensions EXTENSIONS
comma-separated list of file extensions to format, excluding the period and case-insensitive
-f, --force allow changes to unstaged files
-p, --patch select hunks interactively
-q, --quiet print less information
--staged, --cached format lines in the stage instead of the working dir
--style STYLE passed to clang-format
-v, --verbose print extra information
```
## Script for patch reformatting [¶](https://clang.llvm.org/docs/ClangFormat.html#script-for-patch-reformatting "Link to this heading")
The python script clang/tools/clang-format/clang-format-diff.py parses the output of a unified diff and reformats all contained lines with **clang-format**.
```text
usage: clang-format-diff.py [-h] [-i] [-p NUM] [-regex PATTERN] [-iregex PATTERN] [-sort-includes] [-v] [-style STYLE]
[-fallback-style FALLBACK_STYLE] [-binary BINARY]
This script reads input from a unified diff and reformats all the changed
lines. This is useful to reformat all the lines touched by a specific patch.
Example usage for git/svn users:
git diff -U0 --no-color --relative HEAD^ | clang-format-diff.py -p1 -i
svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
It should be noted that the filename contained in the diff is used unmodified
to determine the source file to update. Users calling this script directly
should be careful to ensure that the path in the diff is correct relative to the
current working directory.
optional arguments:
-h, --help show this help message and exit
-i apply edits to files instead of displaying a diff
-p NUM strip the smallest prefix containing P slashes
-regex PATTERN custom pattern selecting file paths to reformat (case sensitive, overrides -iregex)
-iregex PATTERN custom pattern selecting file paths to reformat (case insensitive, overridden by -regex)
-sort-includes let clang-format sort include blocks
-v, --verbose be more verbose, ineffective without -i
-style STYLE formatting style to apply (LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit)
-fallback-style FALLBACK_STYLE
The name of the predefined style used as a fallback in case clang-format is invoked with-style=file, but can not
find the .clang-formatfile to use.
-binary BINARY location of binary to use for clang-format
```
To reformat all the lines in the latest Mercurial/ **hg** commit, do:
```bash
hg diff -U0 --color=never | clang-format-diff.py -i -p1
```
The option -U0 will create a diff without context lines (the script would format those as well).
These commands use the file paths shown in the diff output so they will only work from the root of the repository.
« [ClangCheck](https://clang.llvm.org/docs/ClangCheck.html) :: [Contents](https://clang.llvm.org/docs/index.html) :: [Clang-Format Style Options](https://clang.llvm.org/docs/ClangFormatStyleOptions.html) »
© Copyright 2007-2025, The Clang Team. Created using [Sphinx](https://www.sphinx-doc.org/) 7.2.6.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,238 @@
# clang-format Configuration Skill
A comprehensive skill for configuring clang-format to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# code.
## Navigation
### Quick Access
- [CLI Usage](cli-usage.md) - Command-line tools, flags, and integrations
- [Quick Reference](quick-reference.md) - Common patterns and complete examples
### Style Options by Category
1. [Alignment Options](01-alignment.md) - Align code elements consistently
2. [Breaking & Line Wrapping](02-breaking.md) - Control line breaks and wrapping
3. [Brace Styles](03-braces.md) - Configure brace placement and wrapping
4. [Indentation](04-indentation.md) - Control indentation behavior
5. [Spacing](05-spacing.md) - Fine-tune whitespace placement
6. [Include Organization](06-includes.md) - Sort and organize include directives
7. [Language-Specific](07-languages.md) - Options for specific languages
8. [Comments & Misc](08-comments.md) - Comment formatting and other options
9. [Advanced Options](09-advanced.md) - Experimental and advanced features
### Complete Reference Documentation
- [Full CLI Reference](complete/clang-format-cli.md) - Complete command-line documentation
- [Full Style Options](complete/clang-format-style-options.md) - Complete style configuration reference
## What is clang-format?
clang-format is a tool that automatically formats source code according to configurable style rules. It ensures consistent code formatting across your project and team.
**Supported Languages:**
- C/C++
- Java
- JavaScript/TypeScript
- JSON
- Objective-C
- Protocol Buffers
- C#
- Verilog
- TableGen
## Quick Start
### 1. Create a Configuration File
Generate a `.clang-format` file based on a predefined style:
```bash
clang-format -style=llvm -dump-config > .clang-format
```
**Available Base Styles:**
- `LLVM` - LLVM coding conventions
- `Google` - Google C++ Style Guide
- `GNU` - GNU coding style
- `Chromium` - Chromium project style
- `Microsoft` - Microsoft coding style
- `Mozilla` - Mozilla coding style
- `WebKit` - WebKit coding style
### 2. Customize Your Configuration
Edit `.clang-format` to customize specific options:
```yaml
# Start with a base style
BasedOnStyle: Google
# Customize specific options
IndentWidth: 4
ColumnLimit: 120
PointerAlignment: Left
```
### 3. Format Your Code
```bash
# Format a single file in-place
clang-format -i src/main.cpp
# Format multiple files
clang-format -i src/*.cpp include/*.h
# Check without modifying (dry run)
clang-format --dry-run src/main.cpp
# Format only changed lines in git
git clang-format
```
## Configuration File Structure
A `.clang-format` file uses YAML format with key-value pairs:
```yaml
---
# Language-specific settings
Language: Cpp
# Base style to inherit from
BasedOnStyle: LLVM
# Indentation
IndentWidth: 4
UseTab: Never
TabWidth: 4
# Line length
ColumnLimit: 100
# Braces
BreakBeforeBraces: Allman
# Spacing
SpaceBeforeParens: ControlStatements
# Pointer alignment
PointerAlignment: Left
# Include sorting
SortIncludes: true
```
## Common Workflows
### Format on Commit
Format only staged changes before committing:
```bash
git clang-format
```
### Format Entire Project
```bash
find src include -name '*.cpp' -o -name '*.h' | xargs clang-format -i
```
### Check Formatting in CI
```bash
clang-format --dry-run --Werror src/*.cpp include/*.h
```
### Ignore Specific Files
Create `.clang-format-ignore`:
```text
# Ignore third-party code
third_party/**
external/**
# Ignore generated files
*.pb.cc
*.pb.h
```
## Editor Integration
clang-format integrates with popular editors:
- **VS Code**: Install "Clang-Format" extension
- **CLion**: Built-in support (detects `.clang-format`)
- **Vim**: Use clang-format.py script
- **Emacs**: Use clang-format.el
See [CLI Usage](cli-usage.md) for detailed integration instructions.
## Finding Style Options
Options are organized by category:
- **Need to align assignments?** → [Alignment Options](01-alignment.md)
- **Control where lines break?** → [Breaking & Line Wrapping](02-breaking.md)
- **Configure brace placement?** → [Brace Styles](03-braces.md)
- **Adjust indentation?** → [Indentation](04-indentation.md)
- **Fine-tune spacing?** → [Spacing](05-spacing.md)
- **Organize includes?** → [Include Organization](06-includes.md)
- **Language-specific needs?** → [Language-Specific](07-languages.md)
## Example Configurations
See [Quick Reference](quick-reference.md) for complete configuration examples:
- Google C++ style customized
- Linux kernel style
- Corporate/Microsoft style
- Modern C++ style
## Documentation Structure
This skill is organized into:
1. **Navigable sections** - Categorized options for easy browsing
2. **Complete reference** - Full documentation for deep dives
3. **Quick reference** - Ready-to-use configuration examples
## Best Practices
1. **Version control** your `.clang-format` file in the repository root
2. **Start with a base style** that matches your existing conventions
3. **Make minimal changes** to the base style to reduce maintenance
4. **Document deviations** from standard styles in comments
5. **Test on representative code** before applying project-wide
6. **Use git integration** to format only changed lines
7. **Set up editor integration** for automatic formatting
8. **Create `.clang-format-ignore`** for files that shouldn't be formatted
## Troubleshooting
**Configuration not found?**
- clang-format searches for `.clang-format` or `_clang-format` from the source file's directory upward
- Use `-style=file:/path/to/.clang-format` to specify explicitly
**Unknown options warning?**
- Use `--Wno-error=unknown` to allow formatting with unknown (newer) options
- This happens when your config has options not supported by your clang-format version
**Want to check effective config?**
```bash
clang-format -dump-config file.cpp
```
## Next Steps
- Browse [Style Options by Category](#style-options-by-category) to customize formatting
- Check [Quick Reference](quick-reference.md) for complete working examples
- Review [CLI Usage](cli-usage.md) for advanced command-line usage
- Consult full reference documentation for comprehensive details

View File

@@ -0,0 +1,496 @@
# Quick Reference: Complete Configurations
[Back to Index](index.md) | [CLI Usage](cli-usage.md)
**Navigation:** [Alignment](01-alignment.md) | [Breaking](02-breaking.md) | [Braces](03-braces.md) | [Indentation](04-indentation.md) | [Spacing](05-spacing.md) | [Includes](06-includes.md) | [Languages](07-languages.md) | [Comments](08-comments.md) | [Advanced](09-advanced.md)
Ready-to-use complete clang-format configurations for common scenarios.
> **Note:** This reference is based on Clang v22 documentation. Some options may differ in earlier versions.
## How to Use
Copy the desired configuration to your project's `.clang-format` file:
```bash
# Copy configuration to your project
cat > .clang-format << 'EOF'
# Paste configuration here
EOF
# Test it
clang-format -i src/*.cpp include/*.h
```
## Google C++ Style (Modified)
```yaml
---
Language: Cpp
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 120
# Pointer and reference alignment
PointerAlignment: Left
ReferenceAlignment: Left
DerivePointerAlignment: false
# Line breaking
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLoopsOnASingleLine: false
AllowShortBlocksOnASingleLine: Empty
BreakBeforeBinaryOperators: None
BreakBeforeTernaryOperators: true
# Includes
SortIncludes: CaseSensitive
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^".*\.h"'
Priority: 1
- Regex: '^".*'
Priority: 2
- Regex: '^<.*\.h>'
Priority: 3
- Regex: "^<.*"
Priority: 4
# Braces
BreakBeforeBraces: Attach
# Indentation
IndentCaseLabels: true
IndentPPDirectives: AfterHash
# Spacing
SpaceBeforeParens: ControlStatements
SpacesBeforeTrailingComments: 2
# Comments
ReflowComments: true
FixNamespaceComments: true
# Empty lines
MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: false
```
## Linux Kernel Style
```yaml
---
Language: Cpp
BasedOnStyle: LLVM
# Use tabs
IndentWidth: 8
UseTab: Always
TabWidth: 8
ContinuationIndentWidth: 8
# Column limit
ColumnLimit: 80
# Braces
BreakBeforeBraces: Linux
# Indentation
IndentCaseLabels: false
IndentGotoLabels: false
AccessModifierOffset: -8
# Line breaking
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AllowShortBlocksOnASingleLine: Never
BreakBeforeBinaryOperators: None
# Pointer alignment
PointerAlignment: Right
# Spacing
SpaceBeforeParens: ControlStatements
SpacesInParentheses: false
# Comments
ReflowComments: false
FixNamespaceComments: false
# Alignment
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignTrailingComments: false
# Empty lines
MaxEmptyLinesToKeep: 1
# Preprocessor
IndentPPDirectives: None
```
## Microsoft/Visual Studio Style
```yaml
---
Language: Cpp
BasedOnStyle: Microsoft
IndentWidth: 4
ColumnLimit: 120
# Braces
BreakBeforeBraces: Allman
BraceWrapping:
AfterFunction: true
AfterControlStatement: Always
AfterClass: true
AfterStruct: true
AfterEnum: true
BeforeElse: true
BeforeCatch: true
# Pointer alignment
PointerAlignment: Left
ReferenceAlignment: Left
# Indentation
IndentCaseLabels: false
IndentAccessModifiers: false
AccessModifierOffset: -4
# Line breaking
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
BreakBeforeBinaryOperators: None
# Spacing
SpaceBeforeParens: ControlStatements
SpacesBeforeTrailingComments: 1
# Includes
SortIncludes: CaseSensitive
IncludeBlocks: Preserve
# Comments
ReflowComments: true
FixNamespaceComments: true
# Alignment
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignTrailingComments: true
# Empty lines
MaxEmptyLinesToKeep: 1
```
## Modern C++17/20 Style
```yaml
---
Language: Cpp
BasedOnStyle: LLVM
Standard: c++20
IndentWidth: 2
ColumnLimit: 100
# Pointer alignment
PointerAlignment: Left
ReferenceAlignment: Left
DerivePointerAlignment: false
# Braces
BreakBeforeBraces: Attach
Cpp11BracedListStyle: true
# Breaking
AllowShortFunctionsOnASingleLine: InlineOnly
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AlwaysBreakTemplateDeclarations: Yes
BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
# Indentation
IndentCaseLabels: true
IndentPPDirectives: AfterHash
IndentRequiresClause: true
IndentWrappedFunctionNames: false
# Spacing
SpaceBeforeParens: ControlStatements
SpaceBeforeCpp11BracedList: false
SpacesBeforeTrailingComments: 2
# Includes
SortIncludes: CaseSensitive
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<.*\.h>$'
Priority: 1
- Regex: "^<.*>$"
Priority: 2
- Regex: ".*"
Priority: 3
# Alignment
AlignConsecutiveMacros: true
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignOperands: Align
AlignTrailingComments: true
# Comments
ReflowComments: true
FixNamespaceComments: true
# Empty lines
MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: false
```
## Compact/Dense Style (Minimal Whitespace)
```yaml
---
Language: Cpp
BasedOnStyle: Google
IndentWidth: 2
ColumnLimit: 120
# Braces
BreakBeforeBraces: Attach
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
AllowShortBlocksOnASingleLine: Always
AllowShortEnumsOnASingleLine: true
# Pointer alignment
PointerAlignment: Left
# Breaking
BinPackArguments: true
BinPackParameters: BinPack
BreakBeforeBinaryOperators: None
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
# Spacing
SpaceInEmptyBraces: Never
SpaceBeforeParens: Never
SpacesInParentheses: false
SpacesBeforeTrailingComments: 1
# Indentation
IndentCaseLabels: true
CompactNamespaces: true
# Empty lines
MaxEmptyLinesToKeep: 1
KeepEmptyLinesAtTheStartOfBlocks: false
# Alignment
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignConsecutiveMacros: false
AlignTrailingComments: false
AlignOperands: DontAlign
```
## Readable/Spacious Style
```yaml
---
Language: Cpp
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 100
# Braces
BreakBeforeBraces: Stroustrup
# Pointer alignment
PointerAlignment: Left
# Breaking
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLoopsOnASingleLine: false
AllowShortBlocksOnASingleLine: Never
BinPackArguments: false
BinPackParameters: OnePerLine
BreakBeforeBinaryOperators: NonAssignment
# Spacing
SpaceInEmptyBraces: Block
SpaceAfterCStyleCast: true
SpaceBeforeParens: ControlStatements
SpacesBeforeTrailingComments: 3
MaxEmptyLinesToKeep: 2
KeepEmptyLinesAtTheStartOfBlocks: true
# Indentation
IndentCaseLabels: true
IndentPPDirectives: AfterHash
IndentWrappedFunctionNames: true
# Alignment
AlignConsecutiveMacros:
Enabled: true
AcrossEmptyLines: true
AlignConsecutiveAssignments:
Enabled: true
AlignConsecutiveDeclarations:
Enabled: true
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 1
# Includes
SortIncludes: CaseSensitive
IncludeBlocks: Regroup
# Comments
ReflowComments: true
FixNamespaceComments: true
# Empty lines
EmptyLineBeforeAccessModifier: Always
EmptyLineAfterAccessModifier: Always
```
## Multi-Language Configuration
```yaml
---
# C++ Configuration
Language: Cpp
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 100
PointerAlignment: Left
BreakBeforeBraces: Attach
SortIncludes: CaseSensitive
---
# JavaScript/TypeScript Configuration
Language: JavaScript
BasedOnStyle: Google
IndentWidth: 2
ColumnLimit: 100
JavaScriptQuotes: Single
JavaScriptWrapImports: true
SpacesInContainerLiterals: true
---
# JSON Configuration
Language: Json
IndentWidth: 2
BreakArrays: true
---
# Protocol Buffers Configuration
Language: Proto
BasedOnStyle: Google
IndentWidth: 2
---
# Java Configuration
Language: Java
BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 120
JavaImportGroups:
- com.mycompany
- com
- org
- java
- javax
---
```
## Testing Your Configuration
After creating your `.clang-format` file:
```bash
# Test on a single file
clang-format --dry-run file.cpp
# See what would change
clang-format file.cpp | diff - file.cpp
# Apply formatting
clang-format -i file.cpp
# Format entire project
find src include -name '*.cpp' -o -name '*.h' | xargs clang-format -i
# Check in CI
clang-format --dry-run --Werror src/**/*.{cpp,h}
```
## Configuration Tips
1. **Start with a Base Style**
- Choose a predefined style closest to your preferences
- Only override specific options that differ
2. **Customize Incrementally**
- Apply to a small test file first
- Gradually expand to entire codebase
- Test on representative code samples
3. **Document Your Choices**
- Add comments explaining non-obvious settings
- Maintain a style guide alongside configuration
4. **Version Control**
- Commit `.clang-format` to repository root
- Consider `.clang-format-ignore` for third-party code
5. **Team Adoption**
- Get team consensus before major changes
- Set up editor integration for everyone
- Add pre-commit hooks for enforcement
## Troubleshooting
**Configuration not applied:**
```bash
# Check if clang-format finds your config
clang-format --dump-config file.cpp
```
**Unexpected formatting:**
```bash
# Test with explicit style
clang-format --style=file:/path/to/.clang-format file.cpp
```
**Unknown options (version mismatch):**
```bash
# Allow unknown options
clang-format --Wno-error=unknown -i file.cpp
# Check your version
clang-format --version
```
## See Also
- [Index](index.md) - Main documentation hub
- [CLI Usage](cli-usage.md) - Command-line options
- [All Style Options](index.md#style-options-by-category) - Detailed option documentation
- [Full Style Options Reference](complete/clang-format-style-options.md)
- [Full CLI Reference](complete/clang-format-cli.md)
---
[Back to Index](index.md) | [CLI Usage](cli-usage.md)