如何在Vim中使用左右缩进对齐代码

3wabscal  于 5个月前  发布在  其他
关注(0)|答案(3)|浏览(71)

我有这个代码:

struct
  {
     uint32_t                rsvd0           :  8;
     uint32_t                tag             :  8;       
     uint32_t                status_qualifer : 16;
  } dw0;

字符串
我想把它格式化如下:

struct
  {
     uint32_t                rsvd0 :  8;
     uint32_t                  tag :  8;
     uint32_t      status_qualifer : 16;
  } dw0;


如何在Vim中做到这一点
谢谢

d5vmydt9

d5vmydt91#

我想到了这样的东西:

/\v\s{10}(<\w+>)(\s{2,})?\ze :
:%s//\2\1

字符串
注意:我使用非常神奇的搜索\v,使搜索更容易
在替换部分,我们使用正则表达式groups(),因此我们忽略了第二个单词\s{10}之前的10个空格。您可以更改要删除的空格数。然后我们创建一个与第二个单词(<\w+>)匹配的组。在此之后,两个或更多空格(可选)\s{2,})?。然后,我们通过使用令人敬畏的Vim \ze,一个空格和冒号来完成匹配。
该命令使用最后一个搜索//,它被组2和组1所取代。
我的最终结果是:

struct
  {
     uint32_t                rsvd0 :  8;
     uint32_t                  tag :  8;
     uint32_t      status_qualifer : 16;
  } dw0;


另一种方法涉及两个全局命令,其中第一个命令只是删除列之间的一串空格。

:g/_t/normal wel10x
:g/  :/normal wwelldt:bP


注意:您可以选择上面的行并运行::@+。我已经测试了这些命令,同样适用于第一个解决方案。
第一个全局命令在匹配_t的行上执行正常命令,该命令是:

we ....................... jump to the first word and to the end of it
l ........................ move one position to the right
10x ...................... erases 10 chars


seccond global命令在与:匹配的行上运行,至少有两个空格后跟逗号。

ww ....................... jump to the second word
e ........................ jump to the end of the word
ll ....................... move the cursor twice to the right
dt: ...................... delete until before :
bP ....................... move to the word before and pastes the default register


更多信息:

:h \ze
:h magic
:h regex
:h normal
:h global

2ic8powd

2ic8powd2#

对于对齐,有三个众所周知的插件:

你的问题是一个很好的候选人来评估每个插件。查看他们的文档页面,尝试一个看起来最有前途和理解你。(理想情况下,报告回来,与评论,你选择了哪一个。)

pgccezyw

pgccezyw3#

另一个对齐第二个代码列的正则表达式是:

:%s/\(\s\+\)\(\w\+\)\(\s\+\):/\1\3\2 :/g

字符串
这只是将空格从前面移到第二列后面。

相关问题