Yam Mesicka
Yam Mesicka

Reputation: 6581

Change HTML attribute in neovim

I found myself struggling with quickly changing attributes inside HTML tags.

For example, I have the following code

<div className="expense-date">
  <div className="expense-date__@@@year">{year}</div>
  <div>{month}</div>
  <div>{day}</div>
</div>

My cursor is where the @@@ is, and I want to delete the whole attribute: className="expense-date__@@@year".

Is there any text object I can use to quickly delete it? Currently I use T ct> (or T ct if there's another attribute), but that's obviously not good enough and won't work if there's a space inside the attribute's value.

Upvotes: 1

Views: 592

Answers (3)

SergioAraujo
SergioAraujo

Reputation: 11800

Here's another option:

vi>   ........ visual select inner <>
o ............ jump to the other side
w ............ jump to the next word

Upvotes: 1

romainl
romainl

Reputation: 196546

There is no built-in "attribute" text object but you can approximate one with something generic like this:

va"oB

where:

  • va" selects the value,
  • o moves the cursor to the other side of the selection,
  • B extends the selection to the beginning of the attribute.

This can be turned into quick and dirty pseudo-text objects:

xnoremap ix a"oB
onoremap ix :<C-u>normal vix<CR>
xnoremap ax a"oBh
onoremap ax :<C-u>normal vax<CR>
  • a visual mode mapping that covers the desired text,
  • an operator-pending mode mapping that uses the visual mode one,

to use like this:

yix
dax
vix
cax
…

See this plugin for a much smarter implementation.


Note that nothing in this answer is guaranteed to work in Neovim.

Upvotes: 3

yolenoyer
yolenoyer

Reputation: 9445

To my knowledge, there is no simple way to do this; unless you perform a deep syntax analysis, there will always be some caveats.

You can however improve your technique, for example with F"F=bF d2f".

  • F" goes to the beginning of the string;
  • F= goes to the previous = sign, skipping eventual spaces between;
  • b goes to attribute name (eventualy in the middle of it e.g. for data-my-attr), skipping eventual spaces;
  • F goes to the 1st space before the attribute name;
  • d2f" (or c2f") performs the job.

Of course, you can use it as a macro with q and @ in order to simplify its use.

Upvotes: 1

Related Questions