How to delete everything inside a parenthesis without deleting the parenthesis in Vim? - vim

Let say I have a block of code like this:
await store.dispatch(getLicensesThunk('content', submission))
And I want to delete everything inside the getLicensesThunk excluding the parenthesis, what command should I use?
await store.dispatch(getLicensesThunk())
I currently use d% for this, but it will delete the parenthesis as well, which is not something I want.
await store.dispatch(getLicensesThunk)

d% can't do what you want because it is "inclusive", which means that it includes the characters at the beginning and end of the motion and therefore that it will swallow your parentheses.
Vim has a special kind of motion that can be used after an operator called "text objects". They are described under :help text-object, which is one of the most mind-blowing sections of the built-in documentation.
The one you are looking for is :help i( for "inner parentheses":
di(

Use di( to delete everything inside parentheses. This also works for double quotes (di") and a few more paired characters.
The cursor can be anywhere between the parentheses.

Related

Using "register recall" to search and replace doesn't work when register contains newline character

I've been using the answer to Using visual selection or register for search and replace as follows:
v visually select
y yank
:%s/
Ctrl+r
"
This works fine in most cases. However, if newline characters are part of the visual selection I have to manually replace ^M with \n, first. What am I doing wrong?
What am I doing wrong?
Nothing. It's just Vim being well optimised for some workflows and not for others.
The linked thread actually contains some of the ingredients of the solution to the problem, namely that, after yanking, multiline text needs a bit of massaging if we want to use it for something else than p or P. The massaging is needed because newlines are stored as control characters in the buffer and that's what you get when you yank. But regular expressions don't really like control characters so literal ^#s must be changed into \ns and other characters must be escaped, too, like . or [, because they have a special meaning.
The solution to this problem is thus to write a function that:
escapes what needs to be escaped,
transforms newlines into \ns.
Here is one way to do it (with more intermediary steps than I would do in real life but that's better for demonstration):
function! EscapeRegister(reg)
let raw_text = getreg(a:reg)
let escaped_text = escape(raw_text, '\/.*$^~[]')
return substitute(escaped_text, "\n", '\\n', "g")
endfunction
which you would use like so:
v<motion>
y
:%s/
<C-r>=EscapeRegister(e)<CR>
/foo/g
<CR>
Feel free to call your function ER() or whatever for saving typing.
See :help getreg(), :help escape(), :help substiute(), :help #=.
The function above is fairly low-level and could be composed with other things to make higher-level tools that, for example, could handle everything in the macro above in a couple of keystrokes.

How to delete enclosing braces in Vim?

I have the following text:
Monkeys eat {bananas}.
My cursor is in the middle of the word banana:
Monkeys eat {bana|nas}.
Here the | symbol denotes the cursor's position.
How can I delete the braces from there?
I can change bananas to apples with a simple ci}apples, so perhaps I could use a similar trick just to get rid of the { and } characters?
Also, can I do this even in this case, which is actually what I really need to do?
networks {
local
is|p
}
(The simplified example above was just to introduce the concept.)
Using Tim Pope's excellent surround.vim plugin (which I highly recommend), you would do ds{ for delete surrounding {
I understand that adding another plugin isn't always the ideal solution when you could find a native key sequence instead, but surround.vim is supremely useful, as it can also handle XML/HTML tags and perform enclosures on complex text objects. I regard it as one of those "stuck on a desert island, must have under any circumstance" plugins.
The task can be accomplished by means of Vim built-in text motions.
Delete the text inside the braces, select the braces, and paste the
previously deleted text over them:
di{v%p
What about this:
yiBvaBp
No plugin and simple.
Delete the braces and leave everything else?
mz[{x]}x`z
Expanded
:help m - set a mark. In this case marking the initial cursor position so I can go back there at the end. :help [{ - moves the cursor to the opening brace of the smallest block enclosing the cursor. :help x - delete the brace which is now under the cursor. ]} and x - doing the same to the closing brace. And finally
help `
returning to marked position, the one called z created at the start.
"Plugins" aren't my style...

How to delete a paragraph as quickly as possible

I want to delete the following codes in my config file:
server {
listen 80;
server_name xxx;
location / {
try_files xx;
}
}
I know I can use 7dd, but this is not handy enough- if the section is too long, counting the rows would be inconvenient.
Is there a better way to do this?
Sometimes, I have to delete a whole function, any ideas for that?
As in common in Vim, there are a bunch of ways!
Note that the first two solutions depend on an absence of blank lines within the block.
If your cursor is on the server line, try d}. It will delete everything to the next block.
Within the entry itself, dap will delete the 'paragraph'.
You can delete a curly brack block with da}. (If you like this syntax, I recommend Tim Pope's fantastic surround.vim, which adds more features with a similar feel).
You could also try using regular expressions to delete until the next far left-indented closing curly brace: d/^}Enter
]] and [[ move to the next/previous first-column curly brace (equivalent to using / and ? with that regex I mentioned above. Combine with the d motion, and you acheive the same effect.
If you're below a block, you can also make use of the handy 'offset' feature of a Vim search. d?^{?-1 will delete backwards to one line before the first occurrence of a first-column opening curly brace. This command's a bit tricky to type. Maybe you could make a <leader> shortcut out of it.
Note that much of this answer is taken from previous answer I gave on a similar topic.
If there is a blank line immediately after these lines, Vim will identify it as a paragraph, so you can simply use d} to delete it (assuming the cursor is on the first line).
Try using visual mode with %.
For example, say your cursor is at the beginning of the "server" line.
Press v to go into visual mode. Press % to highlight to the end of the block. Press d to delete it.
As David said their are many ways. Here are a few that I like:
Vf{%d This assumes you are on the line w/ server and you do a visual line selection, find the { and then find the matching } via the % command.
set relativenumber or set rnu for short. This turns on line numbering relative to your cursor. So you do not have to count the lines just look and 7dd away to deleting your block.
Use VaB to visually select a block i.e. { to }, line-wise. While still in visual mode continue doing aB until the proper block is selected then execute d. This means you can select a block from inside the block instead of at the start or end.
d} will delete a paragraph. This works in your current scenario because there is no blank line inside the block. If there is one then all bets are off. Although you can continue pressing . until the block is properly deleted.
If inside a block you can jump to the current block via [{ then continue executing [{ until you are at the correct block then V%d or d%dd to delete the block
Using the techniques above you can delete a function as well, but you can also use the [M and friends ([m, ]m, ]M) to jump to the start and endings of methods but they commonly work for functions as well.
For more information
:h %
:h 'rnu'
:h aB
:h }
:h .
:h [{
:h [m
Given matching parens, or braces, you can use % with d to delete, spanning lines.
So, assuming that you're on the server { line, you can do d%. This is generally useful for all code blocks, e.g. function blocks, loop blocks, try blocks.
Similarly, dip works, but d} is shorter. However, both will only delete to the next empty line.

Is there a good way to copy text within parentheses in Vim?

I want to copy the parameters foo(bar).baz in the following code:
function(foo(bar).baz)
First attempt: Cursor on one of the parentheses, then y%. This gives me the parameters plus a bit extra:
(foo(bar).baz)
Second attempt: Cursor on opening parenthesis. Set a mark ma, jump to end with
% then y`a to copy back to the mark. This gives me:
(foo(bar).baz
Setting a mark at the end and going the other way gives me exactly the same. Setting a
mark on the f, then typing mah%y`a does give me the foo(bar).baz that I want, but maybe there's something more concise. Is there?
Use text objects:
yi( (or ya( if you want to include the parenthesis).
You can also use " to work inside quotes, etc. See the link for details, or type :help text-objects in Vim.
A slightly shorter alternative to yi( is yib. Similarly yiB is equivalent to yi{ - yanks the contents inside braces.
Personally I usually do vib (visual select the text inside braces) first to make sure that the expected text is selected, followed by a y.
For more text object goodness, see :help text-objects.
Following should do it
Yank Inner Block
yi(

In vim, is there a plugin to use % to match the corresponding double quote (")?

The % key is one of the best features of vim: it lets you jump from { to }, [ to ], and so on.
However, it does not work by default with quotes: Either " or ', probably because the opening and closing quote are the same character, making implementation more difficult.
Thinking a bit more about the problem, I'm convinced that it should be implemented, by counting if the number of preceding quotes is odd or even and jumping to the previous or next quote, accordingly.
Before I try to implement it myself, I'd just like to know if someone already has?
Depending on your reason for needing this, there may be a better way to accomplish what you're looking for. For example, if you have the following code:
foo(bar, "baz quux")
^
and your cursor happens to be at the ^, and you want to replace everything inside the quotes with something else, use ci". This uses the Vim "text objects" to change (c) everything inside (i) the quotes (") and puts you in insert mode like this:
foo(bar, "")
^
Then you can start typing the replacement text. There are many other text objects that are really useful for this kind of shortcut. Learn (and use) one new Vim command per week, and you'll be an expert in no time!
Greg's answer was very useful but i also like the 'f' and 'F' commands that move the cursor forward and backward to the character you press after the command.
So press f" to move to the next " character and F" to move to the previous one.
I have found this technique very useful for going to the start/end of a very long quoted string.
when cursor is inside the string, visually select the whole string using vi" or vi'
go to start/end of the string by pressing o
press escape to exit visual select mode
this actually takes the cursor next to the start/end quote character, but still feels pretty helpful.
Edit
Adding Stefan's excellent comment here which is a better option for anyone who may miss the comment.
If you use va" (and va') then it will actually visually select the quotes itself as well.
– Stefan van den Akker
I'd like to expand on Greg's answer, and introduce the surround.vim plugin.
Suppose that rather than editing the contents of your quotes, you want to modify the " characters themselves. Lets say you want to change from double-quotes to single-quotes.
foo(bar, "baz quux")
^
The surround plugin allows you to change this to
foo(bar, 'baz quux')
^
just by executing the following: cs"' (which reads: "change the surrounding double-quotes to single-quotes").
You could also delete the quote marks simply by running: ds" (which reads: "delete the surrounding double-quotes).
There is a good introduction to the surround plugin here.
I know this question is old but here is a plugin to use % to match the corresponding double quote:
https://github.com/airblade/vim-matchquote

Resources