Skip to content

Instantly share code, notes, and snippets.

@YodaEmbedding
Last active November 11, 2024 07:26
Show Gist options
  • Save YodaEmbedding/c2c77dc693d11f3734d78489f9a6eea4 to your computer and use it in GitHub Desktop.
Save YodaEmbedding/c2c77dc693d11f3734d78489f9a6eea4 to your computer and use it in GitHub Desktop.
.clang-format for Rust style (rustfmt)
AccessModifierOffset: -2
AlignAfterOpenBracket: BlockIndent # New in v14. For earlier clang-format versions, use AlwaysBreak instead.
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlines: DontAlign
AlignOperands: false
AlignTrailingComments: false
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: AfterColon
BreakInheritanceList: AfterColon
BreakStringLiterals: false
ColumnLimit: 80
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
FixNamespaceComments: true
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 3
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseLabels: true
IndentPPDirectives: BeforeHash
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
PointerAlignment: Left
ReferenceAlignment: Left # New in v13. int &name ==> int& name
ReflowComments: false
SeparateDefinitionBlocks: Always # New in v14.
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
@YodaEmbedding
Copy link
Author

YodaEmbedding commented Jul 29, 2021

This style tries its best to match Rust style, which is highly readable and maintains conventions found in modern programming styles from other languages. For things that are unique to C++, I have aimed for either maximum clarity, or how I think the Rust style guide would have handled such a situation.

Most options require clang-format v9+ (released in 2019). Some options (e.g. AlignAfterOpenBracket: BlockIndent) may require clang-format v14+ (released in 2022).

Related alternative styles:

Useful links:


The indent size is 4 spaces. If you prefer 2 spaces, run:

sed 's/: 4/: 2/'   -i .clang-format
sed 's/: -2/: -1/' -i .clang-format

Here are some flags that are personal taste, and are not strictly specified by rustfmt, so I chose something reasonable:

Personal taste
AccessModifierOffset
AllowAllConstructorInitializersOnNextLine
AllowShortBlocksOnASingleLine
AlwaysBreakTemplateDeclarations
FixNamespaceComments
IndentCaseLabels
IndentPPDirectives
NamespaceIndentation

Other suggested settings that are not currently in the config above:

BreakAfterAttributes: Always           # v16. [[attribute]] ⏎ void f();
EmptyLineAfterAccessModifier: Never    # v13.
EmptyLineBeforeAccessModifier: Always  # v12.
InsertBraces: true                     # v15. if (true) return;  ==>  if (true) { return; }
InsertNewlineAtEOF: true               # v16.
InsertTrailingCommas: true             # v11. (JavaScript only)
LineEnding: LF                         # v16.
QualifierAlignment: Right              # v14. const int  ==>  int const
RemoveParentheses: Return              # v17. return(0)  ==>  return 0
RemoveSemicolon: true                  # v16.

Future replacement settings for deprecations:

# Deprecated in v14:
# "AllowAllConstructorInitializersOnNextLine: false" and "ConstructorInitializerAllOnOneLineOrOnePerLine: true" 
PackConstructorInitializers: NextLine

# Deprecated in v17:
# "SpaceInEmptyParentheses: true"
SpacesInParens: Custom
SpacesInParensOptions:
  InConditionalStatements: true
  InEmptyParentheses: true

These will be updated in the posted config in a few years once everyone has moved to using newer clang-format versions.


Changelog:

AlignAfterOpenBracket: BlockIndent     # v14. Previously AlwaysBreak. Closing parentheses ); now go on their own line!
AllowShortBlocksOnASingleLine: Empty   # v*. Previously false. Empty blocks {} now go on a single line.
ReferenceAlignment: Left               # v13. New. int &name  ==>  int& name
SeparateDefinitionBlocks: always       # v14.

@thanhph111
Copy link

thanhph111 commented Nov 17, 2021

Should we let AllowShortBlocksOnASingleLine: Empty? It will allow us to do this:

int count = 0;
for (; count < 10; ++count) {}

I've tested with rustfmt, it forces an empty block on the same line.

@julyfun
Copy link

julyfun commented Mar 16, 2023

👍🏻

@beto-bit
Copy link

beto-bit commented Nov 6, 2023

When clang-format 16 is widely supported, you could consider adding BreakAfterAttributes: Always

@Sir-Photch
Copy link

thank you so much for this :)

@elsandosgrande
Copy link

@YodaEmbedding According to https://doc.rust-lang.org/nightly/style-guide/#comments, SpacesBeforeTrailingComments should be set to 1, not 2; to quote: “Prefer to put a comment on its own line. Where a comment follows code, put a single space before it. […]”.

Setting this to 1 also incidentally fixes the formatting of said comments for me when using tabs instead of spaces.

@julyfun
Copy link

julyfun commented Jul 30, 2024

@elsandosgrande
Copy link

elsandosgrande commented Jul 31, 2024

@julyfun Awesome, thanks for sharing! By the way, it appears that Cpp11 is a deprecated alias for Latest, so it's probably best to avoid using it: https://clang.llvm.org/docs/ClangFormatStyleOptions.html#standard

Edit: Also, according to the documentation above, AllowAllConstructorInitializersOnNextLine and ConstructorInitializerAllOnOneLineOrOnePerLine are also deprecated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment