我想定义一个命令来抽象一个具有可变行的复杂表环境。这是一个简单的演示:
\documentclass{article}%
\usepackage{tabularx}%
\begin{document}
\begin{tabularx}{\textwidth}{|X|X|}\hline
name 1 & description 1\\
\hline
name 2 & description 2\\
\hline
\end{tabularx}
\end{document}
根据这个问题@egreg的回答:具有可变数量参数的新命令
我在答案中定义了这样的宏https://tex.stackexchange.com/a/72915:
\makeatletter %
\newcommand{\members}{
\tabularx{\textwidth}{|X|X|} \hline
\@stepone}
\newcommand\@stepone{\@ifnextchar\stopmembers{\@membersend}{\@steptwo}}
\newcommand\@steptwo[2]{
#1 & #2 \\ \hline
\@stepone}
\newcommand\@membersend[1]{
\endtabularx
}
\makeatother
我想像这样使用它:
\begin{document}
\members
{name 1}{description 1}
{name 2}{description 2}
\stopmembers
\end{document}
但是,编译时出现错误:
Misplaced \crcr. \end{document}
Extra }, or forgotten $. \end{document}
Extra }, or forgotten $. \end{document}
Undefined control sequence. \end{document}
Package array Error: Illegal pream-token (\AtEndOfPackage): `c' used. \end{document}
Extra }, or forgotten $. \end{document}
Missing $ inserted. \end{document}
有人能帮助我吗?提前谢谢!
答案1
我不会使用诸如 之类的外国标记\members...\stopmembers
。
我也不知道为什么
{name 1}{description 1}
{name 2}{description 2}
会比
\member{name 1}{description 1}
\member{name 2}{description 2}
无论如何,问题是它tabularx
相当脆弱。
\documentclass{article}
\usepackage{tabularx,environ}
\makeatletter
\NewEnviron{members}{%
\par\noindent
\toks@={}%
\expandafter\start@member\BODY\start@member
\edef\BODY{\noexpand\begin{tabularx}{\textwidth}{|l|X|}
\noexpand\hline
\the\toks@
\noexpand\end{tabularx}}%
\BODY
}
\newcommand\start@member{\@ifnextchar\start@member{\@gobble}{\@member}}
\newcommand{\@member}[2]{%
\toks@=\expandafter{\the\toks@ #1 & #2 \\ \hline}%
\start@member
}
\makeatother
\begin{document}
\begin{members}
{name 1}{description 1}
{name 2}{description 2}
\end{members}
\end{document}
答案2
我想这就是你想要的:
\documentclass{article}
\usepackage{tabularx}
\makeatletter
\newcommand{\members}{\def\@body{}\@stepone}
\newcommand\@stepone{\@ifnextchar\stopmembers{}{\@steptwo}}
\newcommand\@steptwo[2]%
{\expandafter\def\expandafter\@body\expandafter{\@body#1 & #2 \\ \hline}%
\@stepone
}
\newcommand\stopmembers
{\begin{tabularx}{\textwidth}{|X|X|} \hline
\@body
\end{tabularx}%
}
\makeatother
\begin{document}
\noindent
\members
{name 1}{description 1}
{name 2}{description 2}
\stopmembers
\end{document}