Tell clang-format to not add newline after control statement - clang

When I have this minimal program
int main(void) {
for (;;) ;
if (0) return 1;
}
clang-format is adding a new line before the statements:
int main(void)
{
for (;;)
;
if (0)
return 1;
}
How can I tell it to leave control statements without {, as they are. To make an example, when I have
int main(void)
{
for (;;) ;
if (0)
return 1;
}
running clang-format on it should do nothing. I cannot find a configuration option for it. My .clang-format file is:
# SPDX-License-Identifier: GPL-2.0
#
# clang-format configuration file. Intended for clang-format >= 4.
#
# For more information, see:
#
# Documentation/process/clang-format.rst
# https://clang.llvm.org/docs/ClangFormat.html
# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
---
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
#AlignEscapedNewlines: Left # Unknown to clang-format-4.0
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
#AfterExternBlock: false # Unknown to clang-format-5.0
BeforeCatch: false
BeforeElse: false
IndentBraces: false
#SplitEmptyFunction: true # Unknown to clang-format-4.0
#SplitEmptyRecord: true # Unknown to clang-format-4.0
#SplitEmptyNamespace: true # Unknown to clang-format-4.0
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
#BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
#BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
#CompactNamespaces: false # Unknown to clang-format-4.0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
#FixNamespaceComments: false # Unknown to clang-format-4.0
#IncludeBlocks: Preserve # Unknown to clang-format-5.0
IncludeCategories:
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
#IndentPPDirectives: None # Unknown to clang-format-5.0
IndentWidth: 8
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
#ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0
ObjCBlockIndentWidth: 8
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
# Taken from git's rules
#PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0
PenaltyBreakBeforeFirstCallParameter: 30
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyExcessCharacter: 100
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: false
SortIncludes: false
#SortUsingDeclarations: false # Unknown to clang-format-4.0
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
#SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0
#SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0
SpaceBeforeParens: ControlStatements
#SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp03
TabWidth: 8
UseTab: Always
...

Look inside the documentation for OnASingleLine:
https://clang.llvm.org/docs/ClangFormatStyleOptions.html
You will find:
AllowShortBlocksOnASingleLine: [Never | Empty | Always]
AllowShortIfStatementsOnASingleLine: [Never | WithoutElse | OnlyFirstIf | AllIfsAndElse]
And many more for Switch statements, lambdas...

Related

clang-format 15 - force function parameters into new line

I can't force clang-format into spliting function parameters into separate lines:
Current:
virtual void OnSlotSelected(class UArcAbilitySystemComponentBase* InArcASC, class UArcQuickBarComponent* QuickBar, const struct FArcSlotData* InSlot) const {};
Expected:
virtual void OnSlotSelected(class UArcAbilitySystemComponentBase* InArcASC
, class UArcQuickBarComponent* QuickBar
, const struct FArcSlotData* InSlot) const {};
I don't mind where exactly it is aligned (so long as it is consistent).
This my current config:
Language: Cpp
BasedOnStyle: LLVM
BreakConstructorInitializers: BeforeComma
BreakInheritanceList: BeforeComma
AccessModifierOffset: -4
AlignAfterOpenBracket: BlockIndent
PointerAlignment: Left
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: false
BinPackArguments: false
BinPackParameters: false
#ExperimentalAutoDetectBinPacking: true
#PenaltyBreakBeforeFirstCallParameter: 1
#PenaltyBreakOpenParenthesis: 1
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignOperands: true
AlignTrailingComments: false
AlwaysBreakTemplateDeclarations: Yes
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
AfterExternBlock: false
BeforeCatch: true
BeforeElse: true
BeforeLambdaBody: true
BeforeWhile: true
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakBeforeBraces: Custom
ColumnLimit: 0
IncludeCategories:
- Regex: '^<.*'
Priority: 1
- Regex: '^".*'
Priority: 2
- Regex: '.*'
Priority: 3
IncludeIsMainRegex: '([-_](test|unittest))?$'
IndentCaseBlocks: true
IndentCaseLabels: true
IndentWidth: 4
IndentWrappedFunctionNames: true
MacroBlockBegin: ''
MacroBlockEnd: ''
NamespaceIndentation: All
SpacesInAngles: false
TabWidth: 4
UseTab: Always
Remove ColumnLimit, your 0 means unlimited line width (LLVM breaks at 80 characters) so nothing will trigger line break

Clang-Format doesn't indent template functions in header files

I'm having this problem with clang-format not properly indenting my header files. For example, I have a template function in a class and I would expect it to be formatted like so:
template <class T>
class Thing {
public:
T function() {
stuff();
return T;
}
}
I feel like this indentation would happen automatically, however, it doesn't. When I run Clang-format, my function code is indented like this:
template <class T>
class Thing {
public:
T function() {
stuff();
return T;
}
}
How do I get the code in my header files to be formatted like the top one, and not the bottom one?
Below is my .clang-format file:
BasedOnStyle: LLVM
AccessModifierOffset: -4
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: true
AllowShortFunctionsOnASingleLine: Inline
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakTemplateDeclarations: true
BinPackArguments: false
BinPackParameters: false
BreakBeforeBraces: Custom
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
SplitEmptyFunction: false
BreakConstructorInitializers: AfterColon
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 2
Cpp11BracedListStyle: true
DerivePointerAlignment: false
IndentCaseLabels: false
IndentWidth: 4
Language: Cpp
NamespaceIndentation: All
PenaltyBreakBeforeFirstCallParameter: 0
PenaltyBreakComment: 2000
PenaltyBreakString: 3000
PenaltyBreakFirstLessLess: 1000
PenaltyExcessCharacter: 100000
PenaltyReturnTypeOnItsOwnLine: 10000
PointerAlignment: Left
SortIncludes: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesInAngles: false
SpacesInParentheses: false
Standard: Cpp11
UseTab: ForIndentation
I opened your config file in this online clang format generator and looked for settings which would be applicable for your example code.
How does this look ?
BasedOnStyle: LLVM
AccessModifierOffset: '-2'
AllowShortFunctionsOnASingleLine: Inline
BreakBeforeBraces: Custom
BreakConstructorInitializers: AfterColon
ColumnLimit: '80'
ConstructorInitializerIndentWidth: '4'
ContinuationIndentWidth: '2'
IndentWidth: '2'
Language: Cpp
NamespaceIndentation: All
PenaltyBreakBeforeFirstCallParameter: '0'
PenaltyBreakComment: '2000'
PenaltyBreakFirstLessLess: '1000'
PenaltyBreakString: '3000'
PenaltyExcessCharacter: '100000'
PenaltyReturnTypeOnItsOwnLine: '10000'
PointerAlignment: Left
SpaceBeforeParens: ControlStatements
Standard: Cpp11
UseTab: Never
I think maybe the UseTab: Never or AccessModifierOffset: '-2' are the relevant settings. There seems to alos be a relation between IndentWidth: and AccessModifierOffset when the later is bigger than the former indentations get messed up.
If these are not the settings you are looking for zed0 is a easy resource to work with for creating an clang format file one can live with.

What controls break before member function of an object in clang format?

This is the part of of C++ code I want to format with clang-format tool (version 7.0.0).
template <typename Fn>
void AsyncAPI::init_write(std::string const& data, Fn&& callback)
{
errorcode injected(injected_);
injected_ = 0;
if (!injected) { data_ = data; }
std::thread([injected, callback = std::forward<Fn>(callback)]() mutable {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
callback(injected);
})
.detach();
}
The detach() member function of this_thread is somehow moved to a new line. How can I move it one line up, so it looks like
std::thread([]() {
/*
*/
}).detach();
I've quite content with current settings, so I hope the change is not too drastic. I tried predefined format styles provided by clang-format (Google, LLVM), none of them was able to move detach up.
My clang-format config file is,
---
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: false
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: true
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BreakBeforeBinaryOperators: All
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeComma
BreakInheritanceList: BeforeComma
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterFunction: true
AfterNamespace: true
AfterStruct: true
AfterUnion: true
BeforeCatch: true
BeforeElse: false
SplitEmptyFunction: true
BreakStringLiterals: true
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeBlocks: Regroup
IndentCaseLabels: false
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Left
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
...
This seems to be something that broke in clang-format version 5.0.0, and was fixed for version 10.0.0 (verified using the configurator). So, your best bet is to move to clang-format version 10.0.0 or later.

How to tell clang-format do not make short lambda expression on a single line?

#include <iostream>
int main()
{
auto func = []() {
std::cout << "hello, world" << std::endl;
};
func();
}
I would like to keep my short lambda expression in this way. But clang-format always make it on a single line.
auto func = []() { std::cout << "hello, world" << std::endl; };
I have read the documentation but I can't find the correct settings. Here is my configureļ¼š
BasedOnStyle: LLVM
Language: Cpp
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: true
AlignConsecutiveDeclarations: true
AlignEscapedNewlines: Left
AlignOperands: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterClass: true
AfterControlStatement: true
AfterEnum: true
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
BeforeCatch: true
BeforeElse: true
IndentBraces: false
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Custom
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 120
CommentPragmas: '^ IWYU pragma:'
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ]
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
- Regex: '^(<|"(gtest|isl|json)/)'
Priority: 3
- Regex: '.*'
Priority: 1
IndentCaseLabels: true
IndentWidth: 4
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: true
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
ObjCBlockIndentWidth: 4
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: true
SortIncludes: true
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp11
TabWidth: 4
UseTab: Never
My clang-format version is 7.0.0. If the lambda expression have more than two lines, it works well. But when it only one line. clang-format always make it in one line. Sometimes a short function which body only one line, clang-format also make it in one line.
I don't know when this option was added, at least since version 10.0 there is AllowShortLambdasOnASingleLine. See official docs.
In your case you need option's value to be Inline, or Empty, or None.

nearZeroVar in caret returns vary when using foreach

I've noticed that setting foreach=TRUE in nearZeroVar returns a different vector of integers (always seems to be 1) than foreach=FALSE. The metrics returned by saveMetrics=TRUE do not differ. Any suggestions on what I might be missing?
frame = data.frame(seq(1:100),seq(1:100),c(rep(0,99),1))
frame = cbind(frame,frame)
names(frame) = c("a","b","c","d","e","f")
nearZeroVar(frame,allowParallel=TRUE,foreach=TRUE,saveMetrics=TRUE)
freqRatio percentUnique zeroVar nzv
a 1 100 FALSE FALSE
b 1 100 FALSE FALSE
c 99 2 FALSE TRUE
d 1 100 FALSE FALSE
e 1 100 FALSE FALSE
f 99 2 FALSE TRUE
nearZeroVar(frame,allowParallel=TRUE,foreach=FALSE,saveMetrics=TRUE)
freqRatio percentUnique zeroVar nzv
a 1 100 FALSE FALSE
b 1 100 FALSE FALSE
c 99 2 FALSE TRUE
d 1 100 FALSE FALSE
e 1 100 FALSE FALSE
f 99 2 FALSE TRUE
nearZeroVar(frame,allowParallel=TRUE,foreach=TRUE)
[1] 1 1
nearZeroVar(frame,allowParallel=TRUE,foreach=FALSE)
[1] 3 6

Resources