Say I have this line of text in Vim:
(foo bar (baz) qux)
^
and my cursor is on the space between the words foo
and bar
, as indicated. I often find that, in situations like this, I want to delete the entire right-hand side of the outer parenthesized expression (that is, to the right of my cursor), while leaving the left-hand side intact. That is, I'd like to end up with:
(foo)
Usually, I’d accomplish this with dt)
(“delete until )
”), but the addition of a nested parenthetical complicates things: That command would leave me with (foo) qux)
. I could also use d2t)
, but I’d prefer not to have to manually count the number of nested parentheses. I could also use di)
, but that deletes the entire text inside of the parentheses, leaving me with ()
.
Is there a Vim motion with the balance-awareness of the i
- and a
-modified motions that is also relative to the current cursor position?
Press the Esc key to go to normal mode. Place the cursor on the line you want to delete. Type dd and hit Enter to remove the line.
Place your cursor on the first parenthesis, then press v%y or v%d . This means it will select everything between and including the two brackets ( % ) while showing the selection to you visually ( v ) and then yank/copy y or delete/cut d it.
The command dw will delete from the current cursor position to the beginning of the next word character. The command d$ (note, that's a dollar sign, not an 'S') will delete from the current cursor position to the end of the current line. D (uppercase D) is a synonym for d$ (lowercase D + dollar sign). Save this answer.
Make sure you are in the normal mode by pressing Esc . Enter the Visual mode by pressing V . Press G i.e Shift + g to select the text from the cursor to the end of the file . Now press x to delete the selected text .
You can use the ])
motion with d
.
d])
mxF(%d`x
Breaking it down:
mx
Set a mark x
(pick whatever letter you like)
F(
Find previous (
character
%
Jump to matching )
d`x
Delete from here to mark x
That works for your specific case; I'm not sure how general it is. If the previous (
is not on the current line, use ?(<return>
rather than F(
.
EDIT:
I didn't mention d])
because I didn't know about it.
My solution won't work for this case:
( (before) foo (after) )
^
because it jumps back to the nearest (
, not the nearest enclosing (
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With