
這個問題基本上是我一年前發布的兩個舊問題的後續問題,但實際上是試圖找到這個問題的解決方案的結果:
在 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}