【问题标题】:How to indent macros in this manner using a beautifier?如何使用美化器以这种方式缩进宏?
【发布时间】:2015-12-30 13:56:05
【问题描述】:

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

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

【问题讨论】:

  • 你说“礼貌”;我说“ew”
  • @LightnessRacesinOrbit 已修改
  • 我认为它不存在。只需 fork 你喜欢的 beautifer 并自己做,因为它不是众所周知的缩进。
  • @jiandingzhe:另外,您是否知道以这种方式形成的问题目前是题外话? 要求我们推荐或查找书籍、工具、软件库、教程或其他场外资源的问题不属于 Stack Overflow 的主题
  • @GingerPlusPlus 非常棒。那么当我遇到这个问题时,我在哪里可以问这样的问题呢?

标签: clang clang-format


【解决方案1】:

如果您找不到可以完成这项工作的工具,请编写一个可以完成这项工作的工具:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2012-11-04
    • 1970-01-01
    相关资源
    最近更新 更多