将带有评估参数的命令附加到宏

将带有评估参数的命令附加到宏

我正在尝试使用一个命令\appendtocmd来执行此操作:

\def\contents{Files:}
\def\value{yo man}
\appendcmdto{contents}{section}{\value}

内容现在包含"Files: \section{yo man}" ,因此当我在任何地方评估它时,它将显示“文件:”并创建一个部分。还请注意,#3宏在调用时会得到完全评估。

我尝试使用\expandafter、、\expandnext等来实现\csname,但无济于事。如果您知道解决方案,也请解释一下它为什么有效 :)。

答案1

目前还不是很清楚您想要实现什么,但这里有一个\appendcmdto和的定义\xappendto;后者对第三个参数进行了完整的扩展。

\documentclass{article}

\newcommand{\appendcmdto}[3]{%
  \edef#1{%
    \unexpanded\expandafter{#1}%
    \space
    \expandafter\noexpand\csname #2\expandafter\endcsname
    \expandafter{\expandafter\unexpanded\expandafter{#3}}%
  }%
}

\makeatletter
\newcommand{\xappendcmdto}[3]{%
  \protected@edef#1{%
    \unexpanded\expandafter{#1}%
    \space
    \expandafter\noexpand\csname #2\expandafter\endcsname{#3}%
  }%
}
\makeatletter

\def\contents{Files:}
\def\somevalue{yo man}
\def\someothervalue{Ehi! \textbf{\somevalue}}

\appendcmdto{\contents}{section}{\somevalue}

\show\contents

\xappendcmdto{\contents}{subsection}{\someothervalue}

\show\contents

\stop

使用 LaTeX 运行此程序将在终端上显示

> \contents=macro:
->Files: \section {yo man}.
l.28 \show\contents

? 
> \contents=macro:
->Files: \section {yo man} \subsection {Ehi! \protect \textbf  {yo man}}.
l.32 \show\contents

? 

答案2

(不要\value在 LaTeX 中重新定义但是......)

\def\contents{Files:}
\def\value{yo man}
\def\tmp{\appendcmdto{contents}{section}}
\expandafter\tmp\expandafter{\value}

这是假设\appendcmdto在某处定义的(你的问题没有说清楚)

要不就

\makeatletter
\def\contents{Files:}
\def\value{yo man}
\def\tmp#1{\g@addto@macro\contents{\section{#1}}}
\expandafter\tmp\expandafter{\value}

相关内容