2

I have got a custom environment which (sometimes) may not have anything inside it. Under those circumstances I need to take some special actions. Is there a way to check whether my environment is empty?

Here is the first idea, though not very useful I am afraid.

\documentclass{article}

\newenvironment{abletocheckempty}
{
  % Do this if the environment is not empty
  Not empty

  % And do this if the environment is empty
  Empty
}
{
  % No change in closing behavior 
}                              

\usepackage{lipsum}

\begin{document}

\begin{abletocheckempty}
  There is some text or even command here.
  \lipsum[1]
\end{abletocheckempty}

\begin{abletocheckempty}
\end{abletocheckempty}

\end{document}

If we take it a step further, and use the environ package, we can formulate a code like this.

\documentclass{article}

\usepackage{environ}

\usepackage{etoolbox}
\makeatletter
\NewEnviron{abletocheckempty}
{\notblank{\BODY}{Not empty}{Empty}}
\makeatother

\usepackage{lipsum}

\begin{document}

\begin{abletocheckempty}
  There is some texts or even commands here.
  \lipsum[1]
\end{abletocheckempty}

\begin{abletocheckempty}
\end{abletocheckempty}

\end{document}

The above code compiles fine but I get,

Not empty
Not empty

as output.

What is it I could be missing here?

I understand that as stated in the manual for etoolbox,

\ifblank{<string>}{<true>}{<false>}

Expands to <true> if the <string> is blank (empty or spaces), and to <false> otherwise. The <string> is not expanded in the test.

So, I tried using an \expandafter before \notblank, without any avail.

  • 3
    You want \ifdefempty\BODY{<true code>}{<false code>}. When you do \ifblank{\BODY} it counts the tokens in the curly braces which is obviously not empty because there is \BODY even though the replacement text of \BODY would be empty. – Henri Menke Oct 12 '16 at 8:10
6

You could use other etoolbox features as noted in comments, or just test \BODY directly, this makes not empty, empty, empty

\documentclass{article}

\usepackage{environ}

\usepackage{etoolbox}
\makeatletter
\NewEnviron{abletocheckempty}
{\ifx\BODY\@empty
 Empty%
\else
 Not empty%
\fi}
\makeatother

\usepackage{lipsum}

\begin{document}

\begin{abletocheckempty}
  There is some texts or even commands here.
  \lipsum[1]
\end{abletocheckempty}

\begin{abletocheckempty}
\end{abletocheckempty}

\begin{abletocheckempty}\end{abletocheckempty}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.