How to quickly remove a pair of parentheses, brackets, or braces in Vim?

Vim

Vim Problem Overview


In Vim, if I have code such as (in Ruby):

anArray << [anElement]

and my cursor is on the first [, I can hop to ] with the % key, and I can delete all the content between the [] pair with d%, but what if I just want to delete the [ and ] leaving all the remaining content between the two. In other words, what's the quickest way to get to:

anArray << anElement

Vim Solutions


Solution 1 - Vim

Using the Surround plugin for Vim, you can eliminate surrounding delimiters with ds<delimeter>.

To install it via Vundle plugin, add

Plugin 'tpope/vim-surround' 

to your .vimrc file and run :PluginInstall.

Solution 2 - Vim

ma%x`ax (mark position in register a, go to matching paren, delete char, go to mark a, delete char).

EDIT:

%x``x does the same thing (thanks to @Alok for the tip).

Solution 3 - Vim

One can take advantage of the text objects that are built in into Vim (see :help text-objects). The desired edit can be stated as a sequence of the following three actions.

  1. Cut the text inside the square brackets:

     di[
    
  2. Select the (empty) square brackets:

     va[
    

    Alternatively, you can just select the character under the cursor and the one to the left of it, because the command from step 1 always puts the cursor on the closing bracket:

     vh
    
  3. Paste the cut text over the selected brackets:

     p
    

Altogether, it gives us the following sequence of Normal-mode commands:

di[va[p

or, when the alternative form of step 2 is used:

di[vhp

Solution 4 - Vim

If you have issues with the marks pointing to the first char of the line or with using % ...

di[vhp 

works as well... It deletes matching [] brackets, when the cursor is anywhere inside. '[' can be replaced by '{' or '(' .

Solution 5 - Vim

The other answers work fine if you want to delete delimiters one line at a time.

If on the other hand you want to remove a function and it's delimiters from the entire file use:

:%s/function(\(.*\))/\1/g

which replaces function(arguments) with arguments everywhere in the file.

Solution 6 - Vim

You can use d% while your cursor is on the bracket/parentheses.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoshView Question on Stackoverflow
Solution 1 - VimarchmageView Answer on Stackoverflow
Solution 2 - VimJustin SmithView Answer on Stackoverflow
Solution 3 - Vimib.View Answer on Stackoverflow
Solution 4 - VimJanView Answer on Stackoverflow
Solution 5 - VimvimmerView Answer on Stackoverflow
Solution 6 - Vimgenda jungleView Answer on Stackoverflow