tabularx key fails inside a newtcolorbox declared box

Consider the following code:

\documentclass{article}
\usepackage{tabularx}
\usepackage{colortbl}
\usepackage{array}
\usepackage{tcolorbox}

\newtcolorbox{testbox}{
width=.5\textwidth
}

\begin{document}
% \begin{testbox}                      %compilation fails when this is uncommented
%    \begin{tcolorbox}[tabularx={l},width=4cm]
%       test1 \\\hline
%       test2
%   \end{tcolorbox}
% \end{testbox}

\begin{tcolorbox}[width=.5\textwidth]
\begin{tcolorbox}[tabularx={l},width=4cm]
test1 \\\hline
test2
\end{tcolorbox}
\end{tcolorbox}
\end{document}


the testbox declared via newtcolorbox is exactly the same as the tcolorbox with option width=.5\textwidth added manually.

However, while if I put another box with option tabularx into the the latter it works as expected, if I put the same box into my testbox it does not compile anymore.

Any clue on what's happening here?

• no idea what tcolorbox is doing but it's not that surprising that nested constructs fail, there are severe limitations on nesting tabularx in another environment. – David Carlisle Sep 23 '14 at 13:47
• @DavidCarlisle yes, but since the working one is also nested, I was wondering if someone familiar with the internals of the package could explain the difference between the two. – Nico Vecchio Sep 23 '14 at 14:05

The reason for failure in the first case is that the hack for tabularx gets the wrong environment name. This name is stored by the savedelimiter option and is set to testbox by the outer box automatically. For inner boxes, nearly all options are set back to their default values - savedelimiter is one of the very few options which stays at the current value (documented for the reset key).

The example is repaired by using the savedelimiter directly:

\documentclass{article}
\usepackage{tabularx}
\usepackage{colortbl}
\usepackage{array}
\usepackage{tcolorbox}

\newtcolorbox{testbox}{
width=.5\textwidth
}

\begin{document}
\begin{testbox}
\begin{tcolorbox}[tabularx={l},width=4cm,savedelimiter=tcolorbox]
test1 \\\hline
test2
\end{tcolorbox}
\end{testbox}

\begin{tcolorbox}[width=.5\textwidth]
\begin{tcolorbox}[tabularx={l},width=4cm]
test1 \\\hline
test2
\end{tcolorbox}
\end{tcolorbox}
\end{document}


As David Carlisle wrote: Nesting tabularx is a little bit tricky. Here, we nest tabularx inside a tcolorbox inside a tcolorbox...