views:

41

answers:

1

How can I write a (La)TeX command that replaces all [ with { and all ] with }, assuming that every [ has a matching ], and that any braces between the [ and ] are balanced? It needs to be able to deal with nested brackets.

For example, I want to be able to write a command \mynewcommand so that \mynewcommand{{[[{1}{2}][{3}{4}]]}} is the same as \mycommand{{{{{1}{2}}{{3}{4}}}}}.

+2  A: 

Probably the easiest way is to use e-TeX and \scantokens

\newcommand*\mycommand[1]{%
  \begingroup
    \everyeof{\noexpand}%
    \endlinechar=-1\relax
    \catcode`\[=1\relax
    \catcode`\]=2\relax
    \edef\temp{\scantokens{#1}}%
  \expandafter\endgroup
  \expandafter\def\expandafter\temp\expandafter{\temp}%
}

This will define \temp with the material in #1 but with every "[" ... "]" pair turned into a TeX brace group ("{" ... "}"). You can then use \temp to do whatever you want. As I say, this requires e-TeX, which is available in all modern TeX systems.

Joseph Wright