4

I want to have command to insert different heading style based on what environment is currently active. I found that the environment should be accessible via macro \@currenvir, but for me, the "else" branch is executed, so nothing happened.

\newcommand{\head}[1]{
    \ifthenelse{\equal{\@currenvir}{itemize}}{
        \textbf{#1}
    }{

    }   
} 
Werner
  • 603,163
Krab
  • 477

1 Answers1

3

You need to perform a string comparison with the expansion of \@currenvir against itemize. \ifthenelse with the \equal operator does this, but you're short a magic \makeatletter...\makeatother wrapper (see What do \makeatletter and \makeatother do?).

Consider the post Why is the ifthen package obsolete?, I've used the e-TeX \pdfstrcmp to perform a string comparison that is expandable below. If the (numeral) result is 0, we have a match, otherwise it's non-zero:

enter image description here

\documentclass{article}

\makeatletter
\newcommand{\head}[1]{%
  \ifnum\pdfstrcmp{\@currenvir}{itemize}=0
    \textbf{#1}% Inside itemize
  \else
    \textit{#1}% Not inside itemize
  \fi
}
\makeatother
\begin{document}

\begin{itemize}
  \item \head{First} item
\end{itemize}
\begin{enumerate}
  \item \head{Second} item
\end{enumerate}

\end{document}

The above usage should work for nested itemize as well.


You can also use the following \ifx conditional:

\makeatletter
\def\specialenvironment{itemize}
\newcommand{\head}[1]{%
  \ifx\@currenvir\specialenvironment
    \textbf{#1}% Inside "special environment"
  \else
    \textit{#1}% Not inside "special environment"
  \fi
}
\makeatother

Note also the frequent use of %. For the motivation, see What is the use of percent signs (%) at the end of lines?

Werner
  • 603,163