如何在嵌套宏中使用 \appto

如何在嵌套宏中使用 \appto

通过下面的代码,我尝试让宏myexe存储此代码:\colorbox{red}{\parbox{1in}{some text}}但失败了。

我该怎么做?

代码:

\documentclass{article}
\usepackage{etoolbox,xcolor}
\def\fortestpaper{
\usepackage{geometry}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\parindent0pt
}
\fortestpaper
\begin{document}
\def\mycolor{red}
\def\mylength{1in}
\def\myexe{}

% The following code tries to construct \colorbox{red}{\parbox{1in}{some text}}
\appto\myexe{\colorbox}
\eappto\myexe{{\mycolor}}
\appto\myexe{\{}
\appto\myexe{\parbox}
\eappto\myexe{{\mylength}{some text}}
\appto\myexe{\}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\myexe
\end{document}

答案1

\unexpand也许使用一些和\noexpanded内部来连接标记更容易\eappto

\documentclass{article}
\usepackage{etoolbox,xcolor}
\def\fortestpaper{
\usepackage{geometry}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\parindent0pt
}
\fortestpaper
\begin{document}

\def\mycolor{red}
\def\mylength{1in}
\def\myexe{}

% The following code tries to construct \colorbox{red}{\parbox{1in}{some text}}

\eappto\myexe{%
  \noexpand\colorbox{\mycolor}{%
    \noexpand\parbox{\mylength}{%
      \unexpanded{some text}%
    }%
  }%
}

\myexe

\end{document}

在此处输入图片描述

答案2

我无法\eappto在内部分组的情况下工作;但是,我可以从之前进行预扩展\appto以实现所需的结果。

\documentclass{article}
\usepackage{etoolbox,xcolor}
\def\fortestpaper{
\usepackage{geometry}
\geometry{showframe}
\geometry{left=1cm,right=1cm,top=1cm,bottom=1cm}
\parindent0pt
}
\fortestpaper
\begin{document}
\def\mycolor{red}
\def\mylength{1in}
\def\myexe{}

% The following code tries to construct \colorbox{red}{\parbox{1in}{some text}}
\appto\myexe{\colorbox}
\eappto\myexe{\expandafter{\mycolor}}
\expandafter\appto\expandafter\myexe\expandafter{\expandafter{\expandafter
  \parbox\expandafter{\mylength}{some text}}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\myexe

\colorbox{red}{\parbox{1in}{some text}}
\end{document}

在此处输入图片描述

答案3

如果您指的是示例中的\{,作为开始组、结束组,那么您可以使用和来代替它们:\}\bgroup\egroup

\let\ea=\expandafter
\long\def\addto#1#2{\ea\def\ea#1\ea{#1#2}}
\def\eaddto#1{\ea\addto\ea#1\ea}

\def\mycolor{red}
\def\mylength{1in}
\def\myexe{}

\addto\myexe{\colorbox}
\eaddto\myexe{\ea{\mycolor}}
\addto\myexe{\bgroup}
\addto\myexe{\parbox}
\eaddto\myexe{\ea{\mylength}}
\addto\myexe{{some text}}
\addto\myexe{\egroup}

\message{\meaning\myexe}
% macro:->\colorbox {red}\bgroup \parbox {1in}{some text}\egroup

如果您确实想在不同于闭括号的时间插入开括号,那么您必须插入去标记化的变体并\scantokens在使用之前使用\myexe

\let\ea=\expandafter
\long\def\addto#1#2{\ea\def\ea#1\ea{#1#2}}
\def\eaddto#1{\ea\addto\ea#1\ea}

\edef\bopen{\string{} \edef\bclose{\string}}

\def\mycolor{red}
\def\mylength{1in}
\def\myexe{}

\addto\myexe{\colorbox}
\eaddto\myexe{\ea{\mycolor}}
\eaddto\myexe{\bopen}
\addto\myexe{\parbox}
\eaddto\myexe{\ea{\mylength}}
\addto\myexe{{some text}}
\eaddto\myexe{\bclose}

\scantokens\ea{\ea\def\ea\myexe\ea{\myexe}}
\message{\meaning\myexe}
% macro:->\colorbox {red}{\parbox {1in}{some text}}

相关内容