# Multicolumn environment in custom environment

I want to use the multicol-package in my own environment by using a counter, such that it looks like

\newenvironment{Test}{\ifnum\theCnt=1%
\begin{multicols}{1}
\else
\begin{multicols}{2}
\fi}{\end{multicols}}


In theory that is definitely possible, but I want to extend that now, due to having further environments in my Test-environment. It will look like

\begin{Test}
\begin{A}
\end{A}
\begin{B}
\end{B}
\begin{A}
\end{A}
\begin{B}
\end{B}
\end{Test}


Now the interesting part is that environment A and B are modifying the counter, i.e. the first occurence of environment A and B should be set as one-column environments, but every further environment should be set as two-column environment, thus making it not possible to simply modify the environment definition.
As further problem I have that I want to have the second two environments as a single column, i.e. for an input of \begin{Test} \begin{A} \end{A} \begin{B} \end{B} \begin{A} \end{A} \begin{B} \end{B} \begin{A} \end{A} \begin{B} \end{B} \end{Test} the result should look like

  A
B
A   A
B   B


The same effect would be doable if I write

\begin{Test1}
\begin{A}
\end{A}
\begin{B}
\end{B}
\end{Test1}
\begin{Test2}
\begin{A}
\end{A}
\begin{B}
\end{B}
\begin{A}
\end{A}
\begin{B}
\end{B}
\end{Test2}


with Test1 defining a single-column environment, and Test2 a multi-column environment. But I want to have everything in one environment called Test.
Is that possible, and if yes, how?

• If i understand, you want contents of first Aand B in one column then contents of A and B .... in two column? you declare 2 and 3 column. How do A and B change the counter? do you use A, B ,A, B ... always in this ordre? – touhami Mar 20 '16 at 7:45
• @touhami: Yes, A and B are one unit, consisting out of two different environments. The first occurrence of that unit should be in one column, every further in two columns. Fixed that typo in my question above. – arc_lupus Mar 20 '16 at 8:32

Here is a solution. Using environmenthooks from etoolbox

\documentclass{article}
\usepackage{multicol}

\newif\iffirst
\newenvironment{Test}{\section{AB}}{[stuff]}
\newenvironment{A}{\section{A}}{\hrulefill}
\newenvironment{B}{\section{B}}{\dotfill}

\usepackage{etoolbox}
\AtBeginEnvironment{Test}{\firsttrue}
\AfterEndEnvironment{B}{\iffirst\firstfalse\begin{multicols}{2}\fi}
\AtEndEnvironment{Test}{\iffirst\else\end{multicols}\fi}

\begin{document}
bla bla
\begin{Test}
\begin{A}
AAAA
\end{A}

\begin{B}
BBBBB
\end{B}

\begin{A}
AAAA
\end{A}

\begin{B}
BBBBB
\end{B}

\begin{A}
AAAA
\end{A}

\begin{B}
BBBBB
\end{B}
\end{Test}

\begin{Test}
\begin{A}
AAAA
\end{A}

\begin{B}
BBBBB
\end{B}

\end{Test}

\end{document}