Quickest way to change a pair of parenthesis to brackets in vim

kMaster picture kMaster · Aug 20, 2014 · Viewed 11.1k times · Source

I am new to vim and in the process of discovering tons of interesting things that one can using this powerful editor.

One particular thing that I need to do very frequently is to change a pair of parenthesis in the text to square-brackets (for example to change ( (a+b+c) ) to [ (a+b+c) ]) or vice-verso. I now do this by manually changing the two characters ( and ) to [ and ].

However, when there is a lot of text in between the parenthesis, it could be difficult to locate the pair of opening and closing parenthesis especially because after changing the first ( to [ then the % command will no longer be able to find the corresponding ).

I was wondering if there is a better and quicker way to make such changes?

Answer

Lee Hambley picture Lee Hambley · Aug 20, 2014

I personally use https://github.com/tpope/vim-surround as it provides everything I could ever need, reading through the source you can see the solution is non-trivial.

A typical example:

Hello("World")

with the cursor somewhere between the (), you can type cs([ in normal mode to get:

Hello["World"]

surround.vim is easily installed with either Pathogen or Vundle, personally I prefer vundle. https://github.com/VundleVim/Vundle.vim

adding the important commented point:

cs([ adds spaces in the block, this should be cs)]