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

后端 未结 5 855
忘了有多久
忘了有多久 2020-12-12 18:53

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

anArray << [anElement]

and my cursor is on the first [, I can hop to ]

相关标签:
5条回答
  • 2020-12-12 19:25

    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 them:

       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
    
    0 讨论(0)
  • 2020-12-12 19:32

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

    0 讨论(0)
  • 2020-12-12 19:44

    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.

    0 讨论(0)
  • 2020-12-12 19:47

    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.

    0 讨论(0)
  • 2020-12-12 19:48

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

    0 讨论(0)
提交回复
热议问题