用于定义单参数宏的宏

Macro to define single argument macros

我正在尝试定义一个宏来简化以后宏的定义。

我想模拟的行为如下:

\def\mydef#1{MAGIC}

\mydef{foo}
\mydef{bar}

\foo{sometext}% outputs a decorated "foo:sometext"
\bar{sometext}% outputs a similarly decorated "bar:sometext"

我一直在尝试以下内容:

\def\mydef#1{%
  \expandafter\def%      % define when argument is ready
  \csname #1\endcsname%  % set the new macro's handle
  ???%                   % handle arguments to new macro
  {\decorate{#1}{???}}%  % decorate appropriately
}

如何实现这种行为?

在您的实例中,技术上不需要处理 \mydef 中的参数。例如,您可以执行以下操作:

foo:sometext
bar:sometext

\documentclass{article}
\def\mydef#1{%
  \expandafter\def%      % define when argument is ready
  \csname #1\endcsname%  % set the new macro's handle
  {\decorate{#1}}%       % decorate appropriately
}
\newcommand{\decorate}[2]{#1:#2}
\begin{document}

\mydef{foo}
\mydef{bar}

\foo{sometext}% outputs a decorated "foo:sometext"

\bar{sometext}% outputs a similarly decorated "bar:sometext"
\end{document}

\decorate 确实有两个参数,即使您只在 \mydef 创建中传递一个参数。然而,由于 (La)TeX 是一种宏扩展语言,扩展只是将 \decorate{.} 插入输入流,留下 \decorate 来获取它后面的任何内容(两个标记)。

您会看到 \show\foo 将以下内容打印到 .log

> \foo=macro:
->\decorate {foo}.

暗示\foo不接受争论。

如果您确实希望在 \mydef 中将参数捕获为宏创建的一部分,那么您应该 double the #:

\def\mydef#1{%
  \expandafter\def%      % define when argument is ready
  \csname #1\endcsname%  % set the new macro's handle
  ##1%                   % handle arguments to new macro
  {\decorate{#1}{##1}}%  % decorate appropriately
}

\show\foo 现在显示

> \foo=macro:
#1->\decorate {foo}{#1}.

意思是\foo接受一个(强制的)参数。