开发者

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

开发者 https://www.devze.com 2022-12-17 10:47 出处:网络
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 []

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


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).


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


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.


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 '(' .


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消