I would like to define an environment which behaves differently when it is nested. This environment should ignore spaces at the begin and end of the environment. I have this working as I desire when it is not nested. But, when it is nested I can't seem to get the desired behavior.
The first box here is the desired behavior using a non nested version. I would like the second nested version of this environment to behave as if it were not nested. However, there are two issues with the current implementation:
- I am required to add a trailing
%
to\begin{MyBoxedEnvironment}%
when nested. Otherwise I end up with an extra line in between. (See1
in the MWE). - I can not have a blank line following the start of this environment when nested. This can be fixed by manually adding a
\par\noindent
but would prefer not to have to do that. (See2
in the MWE).
As you can see below, I use a counter to count the depth of the nesting, and only \begin
,\end
the mdframed
environment when the counter is zero.
If there is a better way to detect that an environment is nested that would be useful as well.
Code:
\documentclass{article}
\usepackage{xcolor}
\usepackage{mdframed}
\newcommand*{\Text}{%
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Sed accumsan nulla ac ipsum elementum interdum.
Praesent ultricies faucibus turpis, non scelerisque nisi bibendum et.
}%
\newmdenv[%
backgroundcolor=yellow!10,%
linewidth=2pt,%
skipabove=0pt,%
skipbelow=0pt,%
]{MyBoxedEnvironmentMdframed}%
\newcounter{MyBoxEnvironmentDepth}%
\setcounter{MyBoxEnvironmentDepth}{0}% just to be clear we start at 0
\newenvironment{MyBoxedEnvironment}{%
\ignorespaces%
\par\noindent%
\ifnum\value{MyBoxEnvironmentDepth}>0%
% Ignore begin environment since it is nested.
\else%
\begin{MyBoxedEnvironmentMdframed}%
\fi%
\addtocounter{MyBoxEnvironmentDepth}{1}% increment depth
}{%
\addtocounter{MyBoxEnvironmentDepth}{-1}% decrement depth
\ifnum\value{MyBoxEnvironmentDepth}>0%
% Ignore end environment since it is nested.
\else%
\end{MyBoxedEnvironmentMdframed}%
\fi%
\ignorespacesafterend%
}%
\begin{document}
\begin{MyBoxedEnvironment}
\Text
\par\noindent
\textcolor{red}{\Text}
\end{MyBoxedEnvironment}
\begin{MyBoxedEnvironment}
\Text
\begin{MyBoxedEnvironment} % 1. Why space here matter?
% 2. Why does blank line above yield extra line
%\par\noindent% Don't want to have to add this
\textcolor{red}{\Text}
\end{MyBoxedEnvironment}
\end{MyBoxedEnvironment}
\end{document}