对于简单的自定义命令,无法让 xkeyval 按预期工作

对于简单的自定义命令,无法让 xkeyval 按预期工作

我正在尝试使用该xkeyval包来定义一个非常简单的命令,使用键。但是,我对它的行为完全感到困惑,包文档也没有什么帮助。以下是我想要实现的目标(预期)以及我实际得到的结果的 MWE。为什么会发生这种情况,我需要做什么才能得到我想要的结果?我还咨询了:如何创建带有键值的命令?和:使用 xkeyval 的包模板?没有任何运气

\documentclass{article}

\usepackage{xkeyval}

\makeatletter
\define@key[]{fam}{foo}[XX]{#1}
\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   ``Using the macro: \fam@foo ''
   \endgroup
}
\makeatother

\begin{document}

% Example where I hoped to get the default value (XX)
\mycommand % Expected: "Using the macro XX" - Got: "Using the macro"

% Example where I hoped to override the default value
\mycommand[foo=YY] % Expected: "Using the macro YY" - Got: YY "Using the macro"


\end{document}

答案1

当你这样做

\define@key[]{fam}{foo}[XX]{<code>}

你实际上是在做

\def\fam@foo#1{<code>}

就你的情况而言

\def\fam@foo#1{#1}

如果我将代码改为

\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   \texttt{\meaning\fam@foo}\\
   ``Using the macro: \fam@foo ''
   \endgroup
}

获得

在此处输入图片描述

当你执行 时\setkeys[]{fam}{foo}\fam@foo{YY}根据定义,这会扩展为YY。稍后,你执行\fam@foo',这会扩展为'

如果你想保存一个值,你必须说类似的话

\documentclass{article}

\usepackage{xkeyval}

\makeatletter
\define@key[]{fam}{foo}[XX]{\def\fam@foo@toks{#1}}
\setkeys[]{fam}{foo} % initialize
\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   ``Using the macro: \fam@foo@toks ''
   \endgroup
}
\makeatother

\begin{document}

\mycommand

\mycommand[foo=YY]

\end{document}

在此处输入图片描述

另一种方法是使用,它作为容器\define@cmdkey执行上述操作。\cmdfam@foo

\define@cmdkey[]{fam}{foo}{}
\setkeys[]{fam}{foo=XX} % initialize
\newcommand{\mycommand}[1][]{%
   \begingroup
   \setkeys[]{fam}{#1}
   ``Using the macro: \cmdfam@foo''
   \endgroup
}

相关内容