如何在Vim中删除HTML标签而不删除内容

72

我在一个使用打开的文件中,发现了下面这段代码:

<p>Hello stackoverflow!</p>

我该如何删除 <p></p> 标签但保留它们之间的内容?也就是说,我应该按什么键才能得到以下结果:
Hello stackoverflow!

我知道按下d i t会产生相反的效果。
我正在使用Janus
5个回答

106
安装了 surround.vim 插件后,按下 d s t 可以删除周围的标签。
类似的快捷键有:
  • d s ( - 删除括号 ()
  • d s " - 删除双引号 ""
  • d s ' - 删除单引号 ''
等等...

这对我来说是个解决方案。谢谢。 - retro
1
这应该是最受欢迎的答案,因为现在每个人都应该使用 TPopes 很棒的插件! :) - Walialu
我知道 di…da…,但我刚学会了 ds…。太有用了! - Jordi Nebot

100

一个简单的解决方案是(在标签内任何位置放置光标):

yitvatp

这段代码的功能是:

  • y - 复制
  • it - 复制标签内部内容
  • vat - 选择整个标签
  • p - 粘贴之前复制的文本并覆盖标签

非常好的Randy! 我正在使用surround.vim插件,所以Benoit的答案对我来说确实是解决方案。 - retro
1
非常好。我发布了一个补充答案,以提供更多细节。谢谢Randy! - Rob
太棒了!我差点就要问类似的问题了,但是找到了你的答案。谢谢! - Nikolay Fominyh
yitvatp=at 对于强制症患者来说。 - 10gistic

6

我喜欢Randy(+1)的回答,而且我刚学会了标签块!这只是一个补充回答。

所以yit表示“拷贝内部标签块”,vat表示“进入可视模式并选择整个标签块(包括a标签)”。

这只是给那些懒得读帮助文件的人看的:

Tag blocks                      *tag-blocks*

For the "it" and "at" text objects an attempt is done to select blocks between
matching tags for HTML and XML.  But since these are not completely compatible
there are a few restrictions.

The normal method is to select a <tag> until the matching </tag>.  For "at"
the tags are included, for "it" they are excluded.  But when "it" is repeated
the tags will be included (otherwise nothing would change).  Also, "it" used
on a tag block with no contents will select the leading tag.

"<aaa/>" items are skipped.  Case is ignored, also for XML where case does
matter.

In HTML it is possible to have a tag like <br> or <meta ...> without a
matching end tag.  These are ignored.

The text objects are tolerant about mistakes.  Stray end tags are ignored.

4

谢谢,我也看到了。但是我想以与dit相同的方式将其映射到dot。 - retro
1
@retro 通常不建议将其映射到“点”,因为这会遮盖其他非常方便的vim命令,例如“单次重复”。 - Fredrik Pihl

0

我尝试在一个较大的HTML块上使用surround.vim的dst解决方案。它可以工作,但是会将所有子标签缩进到相同的级别。它不应该改变缩进,这会搞乱一切。

Randy的yitvatp解决方案也可以工作,但是在粘贴的标签前后留下了空行。

有没有完美的解决方案?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接