Search code examples
vimtex

How to delete parenthesis in Vim while keeping nested parenthesis intact?


I want to remove a sets of parenthesis in a large tex document I am editing in vim.

The text is of this kind:

\foo{ \bar{ \john{ TEXT } more text } my text}

and I would like to have this as an output if I want to remove \bar

\foo{ \john{ TEXT } more text my text}

clearly a similar expected output in the case for which I want to remove foo is

 \bar{ \john{ TEXT } more text } my text

I have tried via regex (not much of great user)

%s/\\foo{\([^{}]*\)}/\1/gc

and this has resulted in not being able to handle the nested parenthesis as indicated above.

From what I see vim has some way to find corresponding parenthesis as these are highlighted, even when there is nested parenthesis sets. Can this be leveraged some some how?


Solution

  • If this ouput is ok:

    \foo{  \john{ TEXT } more text  my text}
    

    You can use:

    :%norm/\\bar^Mdt{di}va}p
    

    Where ^M is a literal newline character typed via CTRL-V+Enter.

    Explanation:

    • :% for all lines
    • norm run a normal mode command
    • /\\bar search for \bar
    • ^M type enter to run the search
    • dt{ delete until the next {
    • di} delete from within the brace pair
    • va} visually select the empty brace pair
    • p paste the yanked register over the visual selection

    The above works fine by swapping in \foo for the search/deletion as well.


    This is basically an extension of: How to quickly remove a pair of parentheses, brackets, or braces in Vim?

    Pure regex is not well suited for this, as it's intended for regular languages and nesting is generally too complex for it to handle.