基于 ltablex 的 tabularx 的新表环境

基于 ltablex 的 tabularx 的新表环境

我为一些自定义表定义了一个新环境(这样就不必一次又一次地重复标题和列定义等)。

\newenvironment{mytable}{
  \noindent\tabularx{\textwidth}{|c|c|X|} 
    \hline 
    \bf Col 1 & \bf Col 2 & \bf Col 3 \\ 
    \hline
}{%
  \endtabularx
}

它基于 tabularx(用于可变大小的X列),应该能够跨越多个页面。这是包ltablex它可以为 tabularx 环境执行此操作。(请参见tabularx下面示例中的,您可以注释掉mytable)。

但是,我收到错误:

! LaTeX Error: \begin{mytable} on input line 26 ended by \end{tabularx}.

我认为这来自于对它的重新定义,\TX@endtabularx其中ltablex.sty有以下代码片段:

  \ifnum0=`{\fi}%
   \end{tabularx}

是否可以使用“longtable tabularx”作为新环境?

尝试示例:

\documentclass{article}
% filling table with for, relentlessy copied from 
% http://tex.stackexchange.com/a/183756/51583
% extremely shortened, see address for more explanations
\def\addto#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}\def\tabledata{}
\newcount\n\n=1\loop\advance\n by1\addto\tabledata{Lorem&Ipsum&XCell\\}
  \ifnum\n<100\repeat

% package and new environment
\usepackage{ltablex}
\newenvironment{mytable}{%
  \noindent\tabularx{\textwidth}{|c|c|X|} 
    \hline 
    \bf Col 1 & \bf Col 2 & \bf Col 3 \\ 
    \hline
}{%
  \endtabularx
}

\begin{document}

% working tabularx
\begin{tabularx}{\textwidth}{|c|c|X|}
  \tabledata
\end{tabularx}

% not working mytable
\begin{mytable}
  \tabledata
  \hline
\end{mytable}

\end{document}

答案1

tabularx这与处理参数的方式有关。该包environ为这种情况提供了一种解决方法。你不必\newenvironment

\NewEnviron{myenv}{start code
   \BODY
   end code}

然后

\begin{myenv}
  mybody
\end{myenv}

将运行的内容,myenv并将其\BODY替换为mybody。在你的情况下,相关定义是

\usepackage{environ}
\NewEnviron{mytable}{%
  \noindent\begin{tabularx}{\textwidth}{|c|c|X|} 
    \hline 
    \bf Col 1 & \bf Col 2 & \bf Col 3 \\ 
    \hline
  \BODY
\end{tabularx}
}

完整的文件是

\documentclass{article}
% filling table with for, relentlessy copied from 
% http://tex.stackexchange.com/a/183756/51583
% extremely shortened, see address for more explanations
\def\addto#1#2{\expandafter\def\expandafter#1\expandafter{#1#2}}\def\tabledata{}
\newcount\n\n=1\loop\advance\n by1\addto\tabledata{Lorem&Ipsum&XCell\\}
  \ifnum\n<100\repeat

% package and new environment
\usepackage{ltablex}
\usepackage{environ}
\NewEnviron{mytable}{%
  \noindent\begin{tabularx}{\textwidth}{|c|c|X|} 
    \hline 
    \bf Col 1 & \bf Col 2 & \bf Col 3 \\ 
    \hline
  \BODY
\end{tabularx}
}

\begin{document}

% working tabularx
\begin{tabularx}{\textwidth}{|c|c|X|}
  \tabledata
\end{tabularx}

% working mytable
\begin{mytable}
  \tabledata
  \hline
\end{mytable}

\end{document}

相关内容