![根据 \if 宏的状态设置特定的键(和值)](https://linux22.com/image/305714/%E6%A0%B9%E6%8D%AE%20%5Cif%20%E5%AE%8F%E7%9A%84%E7%8A%B6%E6%80%81%E8%AE%BE%E7%BD%AE%E7%89%B9%E5%AE%9A%E7%9A%84%E9%94%AE%EF%BC%88%E5%92%8C%E5%80%BC%EF%BC%89.png)
这个问题基本上是我一年前发布的两个旧问题的后续,但实际上是试图找到该问题的解决方案的结果:
在 biblatex `printbibliography` 中使用切换
\if
我想使用带有语句(伪代码)的键值设置命令
\somekeycommand[\ifdisplay somekey=A \else someotherkey=B]
这样就根据变量的状态设置了一些特定的键\ifdisplay
。
不幸的是,各种方法都不起作用,甚至连\begingroup\edef\x{\endgroup\noexpand....}\x
“窍门”都没有成功。
请注意,我不想要使用
\ifdisplay
\somekeycommand[somekey=A]
\else
\somekeycommand[someotherkey=B]
\fi
实际\somekeycommand
是来自包的一些代码,宏使用\setkeys
这是失败的 MWE
\documentclass{article}
\usepackage{etoolbox}
\usepackage{xparse}
\usepackage{xkeyval}
\makeatletter
\define@key{myfam}{somekey}{%
\def\somekeyvalue{#1}%
}
\define@key{myfam}{someotherkey}{%
\def\somekeyothervalue{#1}%
}
\makeatother
\NewDocumentCommand{\somekeycommand}{+O{}}{%
\begingroup
\setkeys{myfam}{#1}%
\ifdef{\somekeyvalue}{%
Key was \somekeyvalue%
}{%
}%
\endgroup
}%
\newif\ifdisplay
\displayfalse
\begin{document}
\somekeycommand[somekey=A]
\edef\x{%
\expandafter\noexpand\csname ifdisplay\endcsname%
somekey=A%
\noexpand\else%
someotherkey=B%
\noexpand\fi%
}%
\somekeycommand[\x] % fails
\somekeycommand\expandafter[\x] % fails --> expands to [ \expanded value ]
\somekeycommand[\expandafter\begingroup\edef\x{%
\ifdisplay
somekey=A%
\else%
someotherkey=B%
\fi%
}\x] %% -> fails, prints someotherkey=B,
\expandafter\somekeycommand[\begingroup\edef\x{%
\noexpand\ifdisplay
somekey=A%
\noexpand\else%
someotherkey=B%
\noexpand\fi%
}\x] %% -> fails, prints someotherkey=B,
\end{document}
以下是我以前提出的问题:
答案1
请注意,这\setkeys
不会扩展其第二个参数。我不确定你想要什么,但这有效。
\documentclass{article}
\usepackage{etoolbox}
\usepackage{xparse}
\usepackage{xkeyval}
\makeatletter
\define@key{myfam}{somekey}{%
\def\somekeyvalue{#1}%
}
\define@key{myfam}{someotherkey}{%
\def\somekeyothervalue{#1}%
}
\makeatother
\NewDocumentCommand{\somekeycommand}{+O{}}{%
\begingroup
\setkeys{myfam}{#1}%
\ifdef{\somekeyvalue}
{Key was \somekeyvalue}
{\ifdef{\somekeyothervalue}{Other key was \somekeyothervalue}{}}%
\endgroup
}%
\newif\ifdisplay
\displayfalse
\begin{document}
\begingroup\edef\x{\endgroup\noexpand
\somekeycommand\expandafter[\ifdisplay somekey=A\else someotherkey=B\fi]%
}\x
\displaytrue
\begingroup\edef\x{\endgroup\noexpand
\somekeycommand\expandafter[\ifdisplay somekey=A\else someotherkey=B\fi]%
}\x
\end{document}