英文:
VIM - how to add 2 characters at begining and end of a group of words
问题
我想用单个命令在一定数量的单词周围加上**
,而不使用替换(%s...
)。
例如,我想将foo bar baz
变成**foo bar baz**
,只需一个命令即可。我只想替换光标所在的位置。
我知道有插件"surround"(正在测试中),但我想确保没有本机方法可以实现这个目标。
我也可以使用以下方法实现:
:%s/foo bar baz/**&**
但我想知道是否可以通过一个命令快速完成以下步骤:
- 将光标置于第一个单词的开头。
- 插入
**
。 - 移动到第三个单词的末尾。
- 插入
**
。
谢谢。
英文:
I want surround a certain number of words with **
with a single command, without using substitution (%s...
).
For example, I'd like foo bar baz
to turn into **foo bar baz**
with a single command. I want to replace only the occurrence where the cursor is placed.
I know of the plug-in "surround" (testing it right now) but I want to make sure there's no native way to do this.
I can also do it with the following :
:%s/foo bar baz/**%**
But I want to know if the following can be done quickly with one command :
- place the cursor at the beginning of the first word
- insert
**
- go to end of third word
- insert
**
Thanks
答案1
得分: 2
这是要翻译的内容:
首先,这个不会起作用:
:%s/foo bar baz/**%**
因为 %
在这里只是一个字面字符。你可以使用 :help s/\&
或 :help s/\0
来重新使用整个匹配:
:%s/foo bar baz/**&**
:%s/foo bar baz/**:%s/foo bar baz/**&**
:%s/foo bar baz/**:%s/foo bar baz/**&**
:%s/foo bar baz/**\0**
**
**
而且因为它可能在其他地方执行替换,这不是你想要的。
将某些任意文本用其他文本包围的规范方式是:
- 更改文本,
- 插入包围文本的前半部分,
- 插入原始文本,
- 插入包围文本的后半部分,
- 退出插入模式。
在这种情况下,没有内置的运动可以精确覆盖您想要包围的文本,它会像这样:
v{motion}c**<C-r>"**<Esc>
您首先选择 foo bar baz
,然后将其包围起来。
在其他情况下,如果有合适的运动,不需要可视选择:
c{motion}**<C-r>"**<Esc>
请参阅:help c
,:help i_ctrl-r
,和:help registers
。
如果你好奇的话,我已经整理了一份原生方法列表,可以执行 Surround 的功能。 "用文本包围" 可以在没有 Surround 的情况下完成,但复杂性和脆弱性会迅速增加,即使不涉及更复杂的情况。
说真的,只需使用 Surround。
英文:
First off, this won't work:
:%s/foo bar baz/**%**
Because %
is just a literal %
, here. You can reuse the whole match with :help s/\&
or :help s/\0
:
:%s/foo bar baz/**&**
:%s/foo bar baz/**:%s/foo bar baz/**&**
:%s/foo bar baz/**:%s/foo bar baz/**&**
:%s/foo bar baz/**\0**
**
**
And because it could perform the replacement in other places, which is not what you want.
The canonical way to surround some arbitrary text with other text is to:
- change the text,
- insert the first half of the surrounding text,
- insert the original text,
- insert the second half of the surrounding text,
- leave insert mode.
In a case like this, where there is no built-in motion that covers exactly the text you want to surround, it would look like this:
v{motion}c**<C-r>"**<Esc>
where you first select foo bar baz
, and then surround it.
In other cases, when there is a fitting motion, visual selection is unnecessary:
c{motion}**<C-r>"**<Esc>
See :help c
, :help i_ctrl-r
, and :help registers
.
If you are curious, I've put together a list of native ways to do what Surround does. "Surround with text" is doable without Surround, but the complexity and fragility grows rapidly, even without getting into more complex scenarios.
Seriously, just use Surround.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论