有条件地为命令指定可选参数

有条件地为命令指定可选参数

我定义了以下两个新命令:

\usepackage{tcolorbox}

\newcommand{\mycommand}[1]{
    \begin{tcolorbox}[
        center, colback=black!20!white,
        width=.75\textwidth, boxrule=0pt, frame empty]

        #1
    \end{tcolorbox}
}

\newcommand{\othercommand}[1]{
    \begin{tcolorbox}[
        width=.75\textwidth, boxrule=0pt, frame empty]

        #1
    \end{tcolorbox}
}

如您所见,除了第一个命令传递了参数center之外,这两个命令几乎完全相同colback。有没有办法将这两个命令概括为一个可以接受额外参数的命令,并且根据调用时是否存在该参数来呈现任一结果?

答案1

您可以利用适用于同一组级别的\tcbset所有es 的事实。tcolorbox

\documentclass{article}
\usepackage{tcolorbox}

\NewDocumentCommand{\mycommand}{sm}{%
  \begingroup
  \IfBooleanT{#1}{\tcbset{center,colback=black!20!white}}%
  \begin{tcolorbox}[
    width=.75\textwidth,
    boxrule=0pt,
    frame empty
  ]
  #2
  \end{tcolorbox}%
  \endgroup
}

\begin{document}

\noindent X\dotfill X

\mycommand{
  something something something something
  something something something something
  something something something something
}

\mycommand*{
  something something something something
  something something something something
  something something something something
}

\mycommand{
  something something something something
  something something something something
  something something something something
}

\end{document}

*-变体应用centercolback

在此处输入图片描述

答案2

egreg 答案的一个变体,它考虑到可选参数的方括号在未限定的参数中出现时不需要匹配:

\documentclass{article}
\usepackage{tcolorbox}

\NewDocumentCommand{\mycommand}{sm}{%
    \IfBooleanTF{#1}{\begin{tcolorbox}[center, colback=black!20!white, }%
                    {\begin{tcolorbox}[}%
        width=.75\textwidth, boxrule=0pt, frame empty]%
    #2%
    \end{tcolorbox}%
}%

\begin{document}

\noindent X\dotfill X

\mycommand{
  something something something something
  something something something something
  something something something something
}

\mycommand*{
  something something something something
  something something something something
  something something something something
}

\mycommand{
  something something something something
  something something something something
  something something something something
}

\end{document}

在此处输入图片描述

相关内容