[Tex/LaTex] The argument of foo has an extra }.

alignamsmatherrorsexpansion

I'm trying to write a command that does, effectively, an \fbox in something like an align environment. The following code works:

\usepackage{etextools}
\makeatletter
\newcommand*{\alignedfbox}[1]{\@aligedfbox{#1}{}#1&\@endalignedfbox}
\def\@aligedfbox#1#2#3&#4\@endalignedfbox{%
  \ifempty{#4}{%
    \vrule
    \edef\temp{\expandafter\unexpanded\expandafter{\@@aligedfbox{#2#3}#1&\@@endalignedfbox}}%
    \temp
  }{%
    \edef\temp{\expandafter\unexpanded\expandafter{\@aligedfbox{#1}{#2#3}#4\@endalignedfbox}}%
    \temp
  }%
}
\def\@@aligedfbox#1#2&#3\@@endalignedfbox{%
  \underline{\overline{{}#2\vphantom{#1}}}
  \ifempty{#3}{%
    \vrule
  }{%
    &
    \edef\temp{\expandafter\unexpanded\expandafter{\@@aligedfbox{#1}#3\@@endalignedfbox}}%
    \temp
  }%
}

and then

\begin{align*}
  \alignedfbox{1 & = 2}
\end{align*}

However, the \edef\temp{\expandafter\unexpanded\expandafter{...}}\temp sequence is very ugly, and I'm not sure why I need it. (But if I replace it with ..., it fails with the error mentioned in the title of this post, that my arguments to \@alignedfbox/\@@alignedfbox have an extra }. Surprisingly, this error does not occur when I call \@aligedfbox{#1}{}#1&\@endalignedfbox} from \alignedfbox.) I think it has something to do that align and friends gather everything inside the environment into a macro before execution, and something to do with \protect/\protected and how TeX's behavior in expansion-only contexts is different from its behavior in other contexts, but I'm not sure.

What's a replacement for \edef\temp{\expandafter\unexpanded\expandafter{...}}\temp, and what's an explanation for why ... doesn't work by itself, in this instance?

Best Answer

As already suggested, you shouldn't reenvent the wheel ...

\documentclass{article}
\usepackage{mathtools}
\begin{document}

\begin{align*}
  \Aboxed{1 &= 2 }\\
  1 &\ne 2
\end{align*}

\end{document}

enter image description here