如何使用美化器以这种方式缩进宏?

时间:2015-12-30 13:56:05

标签: clang clang-format

我希望我的预处理器以这种方式缩进:

int foo_func()
{
    normal_code();
    normal_code();
#ifdef FOO
#  define aaa
#  define bbb
    code_that_only_foo();
    code_that_only_foo();
#endif
    normal_code_again();
    normal_code_again();
}

我已经尝试了 clang-format ,但它删除了#指令后的所有空格,但我找不到任何控制该行为的选项。那么,clang格式能以这种方式执行预处理器缩进吗?

1 个答案:

答案 0 :(得分:0)

如果找不到能够完成工作的工具,请编写一个工具:

#!/usr/bin/env python3

from sys import stdin
from string import whitespace


def main():
    not_directive = whitespace + '#'
    indentation = 0
    for line in stdin:
        stripped = line.lstrip()
        if stripped.startswith('#'):
            directive = stripped.lstrip(not_directive)
            if directive.startswith('endif'):
                indentation -= 1
            print('#{}{}'.format('  ' * indentation, directive), end='')
            if directive.startswith('if'):
                indentation += 1
        else:
            print(line, end='')


if __name__ == '__main__':
    main()

See it working online

它从stdin中读取源,并将更改的源写入stdout 您可以轻松地使用shell重定向输入和输出。

如果您不了解Python3并希望了解它:

  • string .lstrip( chars )返回 string chars 从中删除了。
    chars 默认为 whitespace
  • 'test' * 0 => '''test' * 1 => 'test''test' * 3 => 'testtesttest'
  • '#{}{}'.format('textA', 'textB') => '#textAtextB'