Vim - How to Select a Text In Between Double Quotes That Has Double Quotes Within It

152 Views Asked by At

If I have the text:

var x = "Hello my name is Jim and I like ice-cream"

It'd be pretty straight forward to use v+i+".

But if my text is:

var x = "Hello my name is "Jim" and I like ice-cream"

When I use v+i+" vim will only highlight Hello my name is. This is an expected behavior.

How would you go about selecting everything within the full sentence Hello my name is "Jim" and I like ice-cream?

3

There are 3 best solutions below

2
Friedrich On

You can still use f and t to jump to a character inclusive or exclusive, respectively. In your use case, position the cursor on the first quote (if it isn't already, move it with e.g. T" or ^f") and do v3t" to visually select everything in the outer quotes.

If counting is not your thing, you can go incrementally with e.g. vt"lt"lt"lt" or similar.

See :help t and :help f.

Since visual mode does not edit anything in itself, there may be non-visual alternatives. If the goal is to change or delete the text in outer quotes, you can :substitute it and take advantage of the greediness of * as in:

:s/".*"/"I like sauerkraut better."

If your goal is to paste the text in quotes somewhere else, I'd be tempted to yank and paste the whole line and remove the quotes and everything outside after pasting.

0
romainl On

How would you go about selecting everything within the full sentence Hello my name is "Jim" and I like ice-cream?

I would do it in three steps:

  1. Curse at the coworker (it can't be past me, right?) who forgot to escape the quotes around Jim (and the various linters and compilers and whatnot that let that crap pass through).
  2. Add the missing backslashes.
  3. And finally do vi".

Rationale: straight quotes don't nest so neither the programming language you are working with nor Vim can know that the second " doesn't close the string started by the first ".

Examples of "correct" strings (YMMV):

"Hello my name is \"Jim\" and I like ice-cream"
"Hello my name is 'Jim' and I like ice-cream"
'Hello my name is "Jim" and I like ice-cream'
`Hello my name is "Jim" and I like ice-cream`
"Hello my name is “Jim” and I like ice-cream"
0
Jens On

As you found out, vi" does not work. What you want to do is

Select everything after the first " to one character left of the last ", independent of the cursor position on the line. Preferably without counting anything.

Then do exactly that with 0f"lv$F"h.

This positions the cursor at the start of the line, finds the first ", moves one to the right, visually selects to the end of the line, reduces the selection to the rightmost " and chops another character to the left. Voilà!