iamnotsam
iamnotsam

Reputation: 10380

Cut or yank an entire tag in VIM

Given a common html bit like

<div>
  <p>
    Mary had a <b>little</b> lamb.
  </p>
</div>

I want to cut the entire (not the inner only) div for pasting elsewhere. I know there are alternative ways to do this like cutting a range of lines etc., but as a newish user of VIM I sorely need to move around tags in my frontend workflow and I just haven't seen a great way to do this yet.

Upvotes: 8

Views: 5066

Answers (4)

romainl
romainl

Reputation: 196546

Use the at text-object to act on a whole tag and the it text-object to act on the content of a tag.

To act on the current text-object, your command should look like this:

operator + text-object

You can add a count before the text-object to act on count levels of surrounding text-objects:

operator + count + text-object

So, with the cursor on line 1 and 5, you can use the following command to yank the whole <div>:

yat

With the cursor on line 2, 3 or 4, the command becomes:

y2at

With the cursor inside the <b>, the command becomes:

y3at

That said, I suggest you use visual mode instead of counting: it's more intuitive, safer and potentially faster. Just repeat the text-object to expand your selection:

vatat

then:

y

See :help motion.txt.

Upvotes: 6

Kent
Kent

Reputation: 195049

xml plugin http://github.com/othree/xml.vim is very handy to edit xml.

with this plugin, when your cursor on <div>, press <leader>D, will remove the <div> till </div> inclusive.

and if you press <leader>d, will only remove the <div> and </div> tag, change your text into:

  <p>
    Mary had a <b>little</b> lamb.
  </p>

there are more functionalities, you may want to check. without the xml plugin, you can press dat

Upvotes: 1

Tom
Tom

Reputation: 16198

With your cusor on the outer div tag: dat

d elete a round t ag

Then paste it with p where you need it.

Upvotes: 28

Amit
Amit

Reputation: 20456

vatyp should do that.

vat to visually select around tag the cursor is in

y to yank it

p to paste. Go to the position where you want to paste and use p to paste.

Upvotes: 3

Related Questions