【问题标题】:In Vim, how to apply macro that involves making a new line to multiple lines在 Vim 中,如何应用涉及将新行转换为多行的宏
【发布时间】:2021-09-02 15:58:59
【问题描述】:

给定:

This is nearly identical 
My answer looks like an o
I am glad you did because
Thank you so much, romain

所需的输出,只需复制该行并在末尾添加2

This is nearly identical 
This is nearly identical 2
My answer looks like an o
My answer looks like an o2
I am glad you did because
I am glad you did because2
Thank you so much, romain
Thank you so much, romain2

我录制了一个宏@q,它将从第一行开始,复制该行(光标现在在第二行),追加2,然后转到下一行(光标现在在第三行线)。如果我一直输入@q 直到文件末尾,宏就可以很好地工作(永远不需要移动光标,宏可以正确处理光标移动)。

但是,如果我尝试使用 :'<,'>norm! @q 方法 (seen here),我得到了这个:

This is nearly identical 
This is nearly identical 2
This is nearly identical 22
This is nearly identical 222
This is nearly identical 2222
My answer looks like an o
I am glad you did because
Thank you so much, romain

【问题讨论】:

标签: vim macros


【解决方案1】:

这是您的 sn-p,但带有行号以帮助您查看问题:

1 This is nearly identical 
2 My answer looks like an o
3 I am glad you did because
4 Thank you so much, romain

范围实际上只是一个行号列表,在本例中为 [1, 2, 3, 4],这意味着您的宏应用于第 1、2、3 和 4 行。

由于您的宏在当前行下方添加了一行,因此之前称为 2 的行现在是 3:

1 This is nearly identical 
2 This is nearly identical 2
3 My answer looks like an o
4 I am glad you did because
5 Thank you so much, romain

你的宏在实际的第 2 行播放:

1 This is nearly identical 
2 This is nearly identical 2
3 This is nearly identical 22
4 My answer looks like an o
5 I am glad you did because
6 Thank you so much, romain

然后在第 3 行:

1 This is nearly identical 
2 This is nearly identical 2
3 This is nearly identical 22
4 This is nearly identical 222
5 My answer looks like an o
6 I am glad you did because
7 Thank you so much, romain

然后在第 4 行:

1 This is nearly identical 
2 This is nearly identical 2
3 This is nearly identical 22
4 This is nearly identical 222
5 This is nearly identical 2222
6 My answer looks like an o
7 I am glad you did because
8 Thank you so much, romain

为了避免这种情况,您必须先标记范围内的每一行。这是通过:help :global 完成的:

:'<,'>g/^/norm! @q

'&lt;,'&gt;g/^/ 标记范围内的每一行,norm! @q 执行宏。

【讨论】:

  • 谢谢,但是,有两件事:[1] 我的宏有 2 个 js 用于转到第三行,但您建议这些动作没有后果,因为下一个宏执行不会是j 的结束位置,而是新的下一行在哪里,对吧? [2] 需要一个链接解释g/^/
  • 1.是的。 2.答案中已经提到:help :global,你还想要什么?
【解决方案2】:

您是否尝试过制作宏,然后4@q

我尝试重新创建你的宏,然后运行4@q

这几乎是一样的 这几乎是一样的 2 我的答案看起来像一个o 我的答案看起来像 o2 我很高兴你这样做了,因为 我很高兴你这样做了,因为 2 非常感谢,罗曼 非常感谢,romain2

这样就不必进行视觉选择。

【讨论】:

    猜你喜欢
    • 2021-11-03
    • 2010-09-28
    • 2016-09-24
    • 2022-01-18
    • 2010-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    • 2022-01-18
    相关资源
    最近更新 更多