我正在尝试设置一个程序,以便迭代格式如下的元素列表[number1][content1][number2][content2]
。以下代码是一个最小的不起作用的示例:(在实际代码中,变量\@list
将通过输入整个文件来定义)。
\documentclass[a4paper,11pt]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[italian]{babel}
\makeatletter
\newif\ifendlist%
\endlistfalse%
\errorcontextlines 10000
\tracingmacros5
\def\@list{[1][A string][1][Another string][2][Yet another one]}
\def\@grabnextelement[#1][#2]{%
\gdef\@elementnumber{#1}%
\gdef\@elementcontent{#2}%
}
\def\@nextelement{%
\@ifnextchar[\@grabnextelement\endlisttrue%
}
\def\@advancelist{%
\expandafter\protected@xdef\expandafter\@list{\expandafter\@nextelement\@list}%
}
\def\printlist{%
\loop\unless\ifendlist%
\@advancelist%
\@elementnumber \hskip 1.5em \@elementcontent
\repeat%
}
\makeatother
\begin{document}
\printlist%
\end{document}
我不明白为什么如果我尝试执行上述代码,会出现错误:
! Argument of \reserved@a has an extra }.
<inserted text>
\par
<to be read again>
}
\iterate ->\unless \ifendlist \@advancelist
\@elementnumber \hskip 1.5em \@e...
\loop ...elax \expandafter \iterate \fi }\iterate
\let \iterate \relax
l.38 \printlist
%
我不是 TeX 专家,但我尝试保护所有 edef 和 xdef。 有人能指出这里发生了什么吗?
有关扩展的更多信息:
\printlist ->\loop \unless \ifendlist \@advancelist \@elementnumber \hskip 1.5em \@elementcontent \par \repeat
\loop #1\repeat ->\def \iterate {#1\relax \expandafter \iterate \fi }\iterate \let \iterate \relax
#1<-\unless \ifendlist \@advancelist \@elementnumber \hskip 1.5em \@elementcontent \par
\iterate ->\unless \ifendlist \@advancelist \@elementnumber \hskip 1.5em \@elementcontent \par \relax \expandafter \iterate \fi
\@advancelist ->\expandafter \protected@xdef \expandafter \@list {\expandafter \@nextelement \@list }
\protected@xdef ->\let \@@protect \protect \let \protect \@unexpandable@protect \afterassignment \restore@protect \xdef
\@list ->[1][A string][1][Another string][2][Yet another one]
\@nextelement ->\@ifnextchar [\@grabnextelement \endlisttrue
\@ifnextchar #1#2#3->\let \reserved@d =#1\def \reserved@a {#2}\def \reserved@b {#3}\futurelet \@let@token \@ifnch
#1<-[
#2<-\@grabnextelement
#3<-\endlisttrue
\reserved@a #10#2{->\expandafter \def \expandafter \it@ccap \reserved@b #10{
我确实看到发生了一些奇怪的事情\reserved@a
,但我不知道如何解决它以及为什么会发生这种情况。
答案1
您不能使用\@ifnextchar
它,\protected@xdef
因为它不能通过扩展来工作,但是您是否需要循环和定义,而不是简单地评估列表?
\documentclass{article}
\begin{document}
\makeatletter
\def\@list{[1][A string][1][Another string][2][Yet another one]}
\def\printlist{\expandafter\printitem\@list[\relax][]}
\def\printitem[#1][#2]{%
\ifx\relax#1%
\else
#1\hskip 1.5em #2\par
\expandafter\printitem
\fi}
\printlist
\end{document}