Search code examples
vimmatchingparentheses

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


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?


Solution

  • I would simply do it like this: %r]^or[.

    Here's an explanation:

    • f( -- put cursor on first parenthesis you want to change (if it's not already there).
    • % -- jump to the matching parenthesis.
    • r] -- replace the parenthesis with a bracket.
    • CTRL-O -- jump back to to first parenthesis.
    • r[ -- replace the parenthesis with a bracket.