0

I am looking for a way to replace

\cmd1{stuff \cmd2{other stuff}}

with

(stuff \cmd2{other stuff})

I have tried

:%s/\\cmd1{\(.\{-}\)}/(\1)/gc

However, this returns

(stuff \cmd2{other stuff)}

since the first } after { is taken because of \{-} -- taking the greedy version does not help, in the case that there is another } later on the line.

Is there a better expression to put inside {\( \)} so that \( \) encompasses everything up to the matching } to {?

2
  • I'm presuming you need it to work for arbitrary numbers of nested cmds? e.g. \cmd1{stuff \cmd2{other stuff \cmd3{even more stuff}}} ?
    – Rich
    Feb 8, 2018 at 15:42
  • And for multiple matches on the line? \cmd1{stuff \cmd2{other stuff}} more stuff \cmd1{even more stuff \cmd2{yet other stuff}}
    – Rich
    Feb 8, 2018 at 16:21

1 Answer 1

1

Regular Expression

If you don't need to be able to support arbitrary levels of nesting, (if there's never a \cmd3 inside your \cmd2), then you can do this by incorporating the inner brackets into your expression, and matching "any character that's not a bracket" [^}] instead of "any character" .:

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

Macro Alternative

Otherwise, you can use a macro instead:

You're using the c confirm flag to inspect every change, so try the following:

  1. /\\cmd1{<Cr>: Find the first \cmd1
  2. qq: Start recording
  3. dt{: delete the \cmd1
  4. %: Jump to matching }
  5. r)``r(: Replace curly brackets with round ones
  6. n: Jump to next match
  7. q: Stop recording

Then press @q to repeat the change, or n to skip this instance and jump to the next. After you've used @q at least once, you can use @@ as a faster shortcut.

If you actually don't want to review the changes as you make them, you can make the macro recursive by changing the recording steps 2–7 to:

qqqqqdt{%r)``r(n@qq

You can then invoke it a single time to make all the changes in one go: @q

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.