TL;DR
Is there some method in Emacs to replace text with nested braces/parentheses?
Example
I had a situation where I had to replace
\dchi{ARG1}{ARG2}
by
\chi^{ARG2}(ARG1)
For simple cases, this is easily be done with query-replace-regexp
,
(query-replace-regexp
"\\\\dchi{\\(?1:.*?\\)}{\\(?2:.*?\\)}"
"\\\\chi^{\\2}(\\1)")
This will however choke on nested-braces structures.
Before replacement: \dchi{\xx{0}{2}}{\yy}
Obtained replacement: \chi^{2}(\xx{1)}{\yy}
Wanted replacement: \chi^{\yy}(\xx{0}{2})
Another example would be refactoring function calls with sub-calls, e.g.
Pattern f1(ARG1, ARG2, ARG3, ARG4)
Replace by f2(ARG4, ARG3, ARG2, ARG1)
Text with nesting f1(A, B, f3(C, D), E)
Wanted replacement f3(E, f3(C, D), B, A)
Likely result f3(D, f3(C, B, A), E)
As I understand, this is simply a case, that goes beyond the capabilities of regular expressions (“they don't count”).
Such one-off use-cases typically are too easily fixed by hand to warrant writing a script that does the brace-matching, yet enough effort to be annoying.
Is there some other tool in emacs, that can help in such cases, or a shell-utility, that makes such generalized-regexp situations easier than writing a script froms scratch?