![为“tabularx”的“newenvironment”包装器传递参数](https://linux22.com/image/440603/%E4%B8%BA%E2%80%9Ctabularx%E2%80%9D%E7%9A%84%E2%80%9Cnewenvironment%E2%80%9D%E5%8C%85%E8%A3%85%E5%99%A8%E4%BC%A0%E9%80%92%E5%8F%82%E6%95%B0.png)
我正在尝试构建一个tabularx
使用 调整行距的环境包装器\newenvironment
。这是我的代码:
\documentclass{article}
\usepackage{tabularx}
\newenvironment{tabularxe}[2]{
\renewcommand{\arraystretch}{1.2}
\begin{tabularx}{#1}{#2}
}{
\end{tabularx}
\renewcommand{\arraystretch}{1}
}
\begin{document}
% intended code
\renewcommand{\arraystretch}{1.5}
\begin{tabularx}{\textwidth}{>{\hsize=0.25\hsize}r|X}
test & text\\
test & text
\end{tabularx}
\renewcommand{\arraystretch}{1}
% erroneous code
\begin{tabularxe}{\textwidth}{>{\hsize=0.25\hsize}r|X}
test & text\\
test & text
\end{tabularxe}
\end{document}
但是此代码会引发错误:
TeX capacity exceeded, sorry [grouping levels=255]. ...larx}{\textwidth}{>{\hsize=0.25\hsize}r|X}
这段代码有什么问题?
答案1
由于tabularx
需要吸收环境的全部内容,因此需要一种特殊的技术来基于它来定义环境,即使用\tabularx
和\endtabularx
,而不是\begin{tabularx}
和\end{tabularx}
。
注意\arraystretch
不需要重置,因为 的效果\renewcommand{\arraystretch}{1.2}
将与 一起结束\end{tabularxe}
。
\hsize
此外,在列中设置r
根本不起作用。
\documentclass{article}
\usepackage{tabularx}
\usepackage{lipsum} % to better show the effect
\newenvironment{tabularxe}[2]{%
\renewcommand{\arraystretch}{1.2}%
\tabularx{#1}{#2}%
}{%
\endtabularx
}
\begin{document}
\noindent
\begin{tabularxe}{\textwidth}{r|X}
text & \lipsum[1][2-5]\\
text & \lipsum[2][2-5]
\end{tabularxe}
\bigskip
\noindent
\begin{tabularx}{\textwidth}{r|X}
text & \lipsum[1][2-5]\\
text & \lipsum[2][2-5]
\end{tabularx}
\end{document}
差别很小,但很明显。