Clang格式将语句体分成多行

gnz*_*lbg 3 c++ formatting clang clang-format

我有以下.cpp文件:

////////////////////////////////////////////////////////////////////////////////
void call_long_function_name(bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) { call_function_name(test); }
  if (test) { sf(test); }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

(斜杠分隔80个字符).使用以下配置文件,clang-format建议:

////////////////////////////////////////////////////////////////////////////////
void call_long_function_name(bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) { 
    call_function_name(test); 
  }
  if (test) { 
    sf(test); 
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

甚至在文件中我允许简短的if语句适合单行.

  • 我设置了错误的选项吗?

  • 我可以使用哪些选项来最小化浪费的垂直空间?

Clang-format的.clang格式文件

BasedOnStyle: Google
AccessModifierOffset: -1
AlignEscapedNewlinesLeft: true
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortFunctionsOnASingleLine: true
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackParameters: true
BreakBeforeBinaryOperators: true
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: true
ColumnLimit: 80
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 2
ContinuationIndentWidth: 0
Cpp11BracedListStyle: true
DerivePointerBinding: true
IndentCaseLabels: true
IndentFunctionDeclarationAfterType: true
IndentWidth: 2
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
PointerBindsToType: true
SpaceAfterControlStatementKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInAngles:  false
Standard: Cpp11
TabWidth: 2
UseTab: Never
Run Code Online (Sandbox Code Playgroud)

小智 7

较新版本的clang-format有一个额外的选项"AllowShortBlocksOnASingleLine",它控制着这种行为.


Sam*_*all 5

似乎clang-format只有在AllowShortIfStatementsOnASingleLine省略括号时才应用该选项.我测试了以下内容:

void call_long_function_name(bool) {}
void call_long_super_duper_long_really_really_long_way_long_function_name(bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) 
    call_function_name(test);
  if (test)
    sf(test);
  if (test)
    call_long_super_duper_long_really_really_long_way_long_function_name(test);
  if (test) {
    return 0;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

得到了:

void call_long_function_name(bool) {}
void call_long_super_duper_long_really_really_long_way_long_function_name(
bool) {}
void sf(bool) {}
int main() {
  bool test = true;
  if (test) call_function_name(test);
  if (test) sf(test);
  if (test)
    call_long_super_duper_long_really_really_long_way_long_function_name(test);
  if (test) {
    return 0;
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)