2

When I use the xcolor package, I can pass the option monochrome, which turns all colors into black. Is it possible to define commands \mono and \notmono that will print their content only if the option monochrome is/isn't given?

Say,

\documentclass{report}
\usepackage[
% monochrome
]{xcolor}    
\newcommand{\notmono}[1]{???} % No idea how to define this
\newcommand{\mono}[1]{???} % No idea how to define this

\begin{document}

\mono{Print this only if option monochrome IS given to xcolor.} \notmono{Print this only if option monochrome is NOT given to xcolor.}

\end{document}

EDIT: I could define

\newcommand{\mono}[1]{}
\newcommand{\notmono}[1]{#1}

in case I do not give the monochrome option, and redefine them when necessary to

\newcommand{\mono}[1]{#1}
\newcommand{\notmono}[1]{}

But I'd still like to know if there is a better way of doing that.

Anna
  • 89

2 Answers2

4

In xcolor's code, there is a \newif command \ifcolors@ that is true by default and set to false when the monochrome option is used. So you could define your commands \notmono and \mono to check \ifcolors@.

\documentclass{report}
\usepackage[
% monochrome
]{xcolor}
\makeatletter
\newcommand{\notmono}[1]{\ifcolors@#1\else\fi}
\newcommand{\mono}[1]{\ifcolors@\else#1\fi}
\makeatother

\begin{document}

\mono{Print this only if option monochrome IS given to xcolor.} \notmono{Print this only if option monochrome is NOT given to xcolor.}

\end{document}

The above example outputs

Uncommenting the monochrome option, it rather outputs

as expected.

Vincent
  • 20,157
2

In order to avoid problems with \if..-\else-\fi-nesting in case the argument of \mono/\notmono contains unbalanced \if..-\else-\fi-expressions you can fork between gobbling/delivering the argument:

\documentclass{report}
\usepackage[%
%monochrome
]{xcolor}

\makeatletter \newcommand{\mono}{\ifcolors@\expandafter@gobble\else\expandafter@firstofone\fi} \newcommand{\notmono}{\ifcolors@\expandafter@firstofone\else\expandafter@gobble\fi} %\newcommand{\notmono}{\expandafter\unless\mono} \newcommand\CheckWhetherMono{\ifcolors@\expandafter@secondoftwo\else\expandafter@firstoftwo\fi} \makeatother

\begin{document}

\mono{Print this only if option monochrome IS given to xcolor.} \notmono{Print this only if option monochrome is NOT given to xcolor.}

\CheckWhetherMono{Print this only if option monochrome IS given to xcolor.}% {Print this only if option monochrome is NOT given to xcolor.}

Now the weird things that malevolent users might do:

\iftrue \mono{\fi Print this only if option monochrome IS given to xcolor.} \notmono{\fi Print this only if option monochrome is NOT given to xcolor.}

\iftrue \CheckWhetherMono{\fi Print this only if option monochrome IS given to xcolor.}% {\fi Print this only if option monochrome is NOT given to xcolor.}

\end{document}

enter image description here

enter image description here

Ulrich Diez
  • 28,770