如何通过clang-format为复杂赋值表达式中的Lambda缩进4个空格
问题描述
现有一段经clang-format格式化后的C++代码:
auto typeParams = node->typeParams | std::views::transform([&](auto p) { return m_irCtx.make(IRGenericType(p)); });
期望将其格式化为:
auto typeParams = node->typeParams | std::views::transform([&](auto p) { return m_irCtx.make(IRGenericType(p)); });
已知设置LambdaBodyIndentation为OuterScope无效果,询问.clang-format中控制Lambda相对于父作用域缩进的选项及实现方式。
解决方案
控制Lambda主体相对于父作用域缩进的核心选项是LambdaBodyIndentation,但单独设置OuterScope无效时,是因为Lambda处于函数调用的续行参数中,续行缩进的配置会干扰最终效果,需要配合以下两个选项调整:
LambdaBodyIndentation: OuterScope:强制Lambda主体的缩进级别与外层作用域保持一致,而非跟随Lambda所在的续行位置缩进。ContinuationIndentWidth:将该值设置为与IndentWidth相同的数值(例如均设为4),避免续行的Lambda定义额外增加缩进量。
最终的.clang-format配置示例:
IndentWidth: 4 ContinuationIndentWidth: 4 LambdaBodyIndentation: OuterScope
应用该配置后,clang-format会将Lambda主体的代码缩进调整为与外层作用域一致的宽度,达到你期望的格式化效果。
内容的提问来源于stack exchange,提问作者thebear8
相关产品推荐
相关产品推荐

