【问题标题】:clang-format keeps toggling comment locationclang-format 不断切换评论位置
【发布时间】:2020-02-28 18:18:00
【问题描述】:

我在源文件上运行clang-formt,它不断切换评论的位置,从未确定正确的位置。

这是我的.clang-format 文件的副本:

BasedOnStyle: Microsoft

版本信息:

$ clang-format --version
clang-format version 9.0.0

下面的 sn-p 显示了当我运行 clang-format-i 然后 --output-replacements-xml 时的结果:

$ clang-format -i MyFile.cpp
$ clang-format --output-replacements-xml MyFile.cpp
<?xml version='1.0'?>
<replacements xml:space='preserve' incomplete_format='false'>
<replacement offset='2702' length='7'>&#10;            </replacement>
</replacements>
$ clang-format -i MyFile.cpp
$ clang-format MyFile.cpp
<?xml version='1.0'?>
<replacements xml:space='preserve' incomplete_format='false'>
<replacement offset='2702' length='13'>&#10;      </replacement>
</replacements>

如您所见,替换偏移量的长度字段不断变化。如果我一遍又一遍地运行这个,你会看到它在上面列出的两个结果之间交替出现。本质上,它只是来回移动特定评论的位置。

这里是有问题的来源:

格式化版本 1:

    if (mp) // if foo bar likes to foo, the foo
    {       // but bar foo also is bar
            // too bizz bazz buzz bizz
        status = contains(mp->foobar());

格式化版本 2:

    if (mp) // if foo bar likes to foo, the foo
    {       // but bar foo also is bar
      // too bizz bazz buzz bizz
        status = contains(mp->foobar());

有问题的线路是// too bizz bazz buzz bizz,因为它的位置永远不会“确定”。有谁知道为什么这条评论不断来回移动?此外,关于如何防止这种情况的任何想法(更改格式文件、不同版本的格式化程序等)。

【问题讨论】:

    标签: c++ clang code-formatting clang-format


    【解决方案1】:

    显然这是clang-format 中的一个错误。我发现的唯一解决方法是移动第三个注释行。

    • 如果您从与后续代码行对齐的最后一行注释开始:
          if (mp) // if foo bar likes to foo, the foo
          {       // but bar foo also is bar
              // too bizz bazz buzz bizz
              status = contains(mp->foobar());
      
      然后就不动了。但如果初始缩进是其他内容,它会像您发现的那样切换。
    • 如果您设置ReflowComments: false,则第三个注释行的缩进不会切换,但缩进确实需要两次往返才能解决。 clang-format 的第一次调用将注释与其他 cmets 对齐。第二次调用将其与后续代码对齐。之后它就不动了,就像上面的子弹描述的那样。总的来说,这是非常奇怪的行为,我认为它会在 clang-format 的后续版本中得到更改/修复。

    【讨论】:

      猜你喜欢
      • 2016-05-20
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 1970-01-01
      • 2011-05-20
      • 2016-01-03
      • 1970-01-01
      • 2017-09-14
      相关资源
      最近更新 更多