当我使用该xcolor
包时,我可以传递选项monochrome
,将所有颜色变为黑色。是否可以定义命令\mono
,并且\notmono
仅在给出/不给出选项单色时才打印其内容?
说,
\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}
编辑:我可以定义
\newcommand{\mono}[1]{}
\newcommand{\notmono}[1]{#1}
以防我没有给出monochrome
选择,并在必要时重新定义它们
\newcommand{\mono}[1]{#1}
\newcommand{\notmono}[1]{}
但我仍然想知道是否有更好的方法来做到这一点。
答案1
在 的代码中xcolor
,有一个\newif
命令\ifcolors@
默认为 true,monochrome
使用该选项时设置为 false。因此,您可以定义自己的命令\notmono
并\mono
进行检查\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}
上述示例输出
取消注释该monochrome
选项,它会输出
正如预期的那样。
答案2
为了避免在/的参数包含不平衡的- - -表达式的情况下出现\if..
- - \else
-嵌套问题,您可以在吞噬/传递参数之间进行分叉:\fi
\mono
\notmono
\if..
\else
\fi
\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}