0

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

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-format 可以以这种方式执行预处理器缩进吗?

4

1 回答 1

0

If you cannot find a tool that does the job, write a tool that does:

#!/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

It reads the source from the stdin, and writes changed source to the stdout.
You can easily redirect input and output with shell.

If you don't know Python3 and wish to understand it:

  • string.lstrip(chars) returns string with chars removed from it's beggining.
    chars defaults to whitespace.
  • 'test' * 0 => '', 'test' * 1 => 'test', 'test' * 3 => 'testtesttest'
  • '#{}{}'.format('textA', 'textB') => '#textAtextB'
于 2015-12-30T16:02:28.870 回答