3

As the title states I want to save a tabularx in a box. Usually I would use this approach to save it in a box and later on typeset it. But the problem is that want to use it in an environment.

So the naive approach which works with tabular, but not tabularx would be:

\documentclass{article}
\usepackage{xparse}
\usepackage{tabularx}

\newsavebox{\mybox}
\ExplSyntaxOn
\NewDocumentEnvironment{strange}{}
    {
        \begin{lrbox}{\mybox}
        \tabularx{\textwidth}{|l|ll|}
    }
    {
        \endtabularx
        \end{lrbox}
    }
\ExplSyntaxOff

\begin{document}

\begin{strange}
x & y & z\\\hline
\end{strange}

\end{document}

Question: Is it even possible to get a tabularx saved into a box, and if yes, how?

I'm adding the tag here, because this environment will be defined in expl3 context. So any solution with l3box is appreciated too.

TeXnician
  • 33,589

2 Answers2

4

enter image description here

\documentclass{article}
\usepackage{xparse}
\usepackage{tabularx}

\newsavebox{\mybox}
\NewDocumentEnvironment{strange}{}
    {%
        \lrbox\mybox
        \tabularx{\textwidth}{|X|ll|}%
    }
    {%
        \endtabularx
        \endlrbox
    }

\begin{document}

\begin{strange}
x & y & z\\\hline
\end{strange}


\hrule

\begin{center}
\usebox\mybox
\end{center}

\end{document}

\tabularx needs to know which environment name will appear in \end{....} in the source file, so that it can grab the environment body, if you nest a \begin{lrbox} then it wants to see \end{lrbox} but that isn't there.

David Carlisle
  • 757,742
  • 1
    The \hrule is confusing here, in my point of view -- the screen shot indicates that there is a spacing between the upper rule and the real tabular content, not everybody will notice the \hrule there –  Jan 05 '18 at 11:54
  • @ChristianHupfer I added it to show that the printed output comes from the usebox (after the rule) rather than (as would happen in some bad implementations) directly at the environment if it failed to save into a box. – David Carlisle Jan 05 '18 at 11:57
  • Sorry, my mistake; the error was invalid input. Hence you get the tick, because no extra package is needed ;) – TeXnician Jan 05 '18 at 12:02
2

In order to use tabularx you must have no \begin in the “start” part of the new environment definition. On the other hand using \lrbox instead of \begin{lrbox} is not recommended, see https://tex.stackexchange.com/a/125954/4427.

If you're not going to nest strange environments, the easiest workaround is with environ.

\documentclass{article}
\usepackage{environ}
\usepackage{tabularx}

\newsavebox{\mybox}

\NewEnviron{strange}[\textwidth]{%
  \begin{lrbox}{\mybox}%
  \begin{tabularx}{#1}{|l|ll|}\BODY\end{tabularx}%
  \end{lrbox}%
}

\begin{document}

\begin{strange}
x & y & z\\\hline
\end{strange}

\end{document}

You can also call \begin{strange}[10cm] (or any other length).

egreg
  • 1,121,712