1

How can I search and replace in a region of a (TeX)buffer all occurences of \macro{foo}_{bar} to \macro{foo_{bar}}, foo and bar not being "constants" ?

1 Answer 1

1

Use regexp replacement (M-x replace-regexp or C-M-%) to replace a pattern with holes.

Assuming that foo and bar do not themselves contain braces or line breaks, replace \\macro{\(.*?\)}_{\(.*?\)} by \\macro{\1_{\2}}. Explanations (see the manual for more details):

  • \ is a special character, so you need to write \\ to match one backslash.
  • \(…\) is a group: Emacs will remember what the group matched.
  • .*? matches any sequence of characters except a line break. It stops as early as possible (whereas .* would stop as late as possible, and could thus end up matching all of \macro{foo}_{bar} and more \stuff{baz}).
  • In the replacement, \1 and \2 are replaced by what the corresponding group matched.
1
  • Works like a charm. Thank you so much.
    – cjorssen
    Commented Nov 15, 2022 at 21:07

Your Answer

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

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