Custom environment for tcolorbox not working with certain option

environmentsequationserrorshighlightingtcolorbox

I have trouble defining a custom environment for a tcolorbox equation environment. When I define an environment for my tcolorbox with ams align Option I get the error:

LaTeX Error: \begin{tcolorbox} on input line 494 ended by \end{myenv}. (\end{myenv} 

With the answer from LaTeX Error: \begin{tcolorbox} on input line x ended by \end{myenv} when using new environment I thought I could solve it. But while the example from this question works, mine doesn't.

So it works to use this environment

 \newenvironment{myenv}
 {\tcolorbox[hbox]}
   {\endtcolorbox}

but when I use this:

\newenvironment{myenv}
{\tcolorbox[ams align]}
  {\endtcolorbox}

I get the above error. What is wrong and how can I solve this?

Best Answer

When starting an environment foo by writing \begin{foo} a couple of things happen; among these, the current environment's name is stored in the macro \@currenvir, and then the macro \foo is expanded. That's the reason why when defining wrappers for environments it's always a good idea to use the internal macros \foo and \endfoo: in this way you (usually) get clearer error messages.

However, tcolorbox does things differently, and the macro \tcolorbox (more exactly, some other macro a couple of expansions later) also sets \@currenvir:

\documentclass[twocolumn]{article}% twocol for smaller snapshot

\usepackage{tcolorbox}

\begin{document}

\csname@currenvir\endcsname
\begin{center}
\csname@currenvir\endcsname
\end{center}
\csname@currenvir\endcsname
\begin{tcolorbox}
\csname@currenvir\endcsname
\end{tcolorbox}

\end{document}

enter image description here

I don't quite know the rationale behind this choice, but I guess that's (also) why a tcolorbox version of \newenvironment is provided, namely \newtcolorbox:

\documentclass{article}

\usepackage{tcolorbox}
\tcbuselibrary{theorems}

\newtcolorbox{myenv}{ams align}

\begin{document}

\begin{myenv}
a &= b & c&= d \\
e &= f
\end{myenv}

\end{document}

enter image description here

Related Question