如何在 VIM 中将代码与左右缩进对齐

How to align code with left and right indentaion in VIM

我有这个代码:

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 中执行此操作。

谢谢

对齐,比较有名的插件有3个:

您的问题很适合评估每个插件。查看他们的文档页面,尝试看起来最有前途和最容易理解的那个。 (最好在此处反馈,并附上您选择的评论。)

我想到了这样的事情:

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

注意:我使用非常神奇的搜索 \v 来简化搜索

在替换部分我们使用正则表达式组 (),所以我们忽略了第二个单词 \s{10} 之前的 10 spaces。您可以更改要删除的 space 的数量。 然后我们正在创建一个匹配第二个单词 (<\w+>) 的组。接下来是两个 space 或更多(可选)\s{2,})?。然后,我们使用令人敬畏的 vim \ze、space 和冒号

来完成匹配

该命令使用最后一次搜索 // 替换为第 2 组,然后是第 1 组。

我的最终结果是:

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

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

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

注意:您可以 select 上面的行和 运行::@+。我已经测试了这些命令,这同样适用于第一个解决方案。

第一个全局命令在匹配 _t 的行执行普通命令 命令是:

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

第二个全局命令 运行 超过匹配 : 的行 至少两个 space 之后是昏迷。

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