tabularx 包装器环境中的底部 hline

tabularx 包装器环境中的底部 hline

我想为表格定义一个包装器环境,其中一列会拉伸以填充可用宽度。我正在使用包tabularx及其X列来实现这一点。如上所述这里并且在tabularx文档中,我需要在我的环境定义中使用\tabularx...\endtabularx而不是\begin{tabularx}... ,因为运行到封闭环境的末尾。\end{tabularx}\tabularx

到目前为止一切顺利,现在我想在顶部和底部添加水平线。当我\hline在环境定义中注释掉底部时,我收到错误

! Misplaced \noalign.
\hline ->\noalign 
                  {\ifnum 0=`}\fi \hrule \@height \arrayrulewidth \futurelet...
l.28 \end{mytable}

MWE(\hline注释掉了想要的但是有问题的部分):

\documentclass{article}
\usepackage{array}
\usepackage{tabularx}
\newenvironment{mytable}{%
  \tabularx{\textwidth}{lX}
    \hline%
    Name & Description \\
    \hline%
}{%
  %\hline%
  \endtabularx%
}

\begin{document}
Manually (working fine): \\
\begin{tabularx}{\textwidth}{lX}
  \hline
  Name & Description \\
  \hline
  foo & This description is long. It is very long. It is more than one line long. It is automatically broken up into lines. \verb`\verb` works. \\
  \hline
\end{tabularx}

\medskip
Wrapper environment (error with the bottom \verb`\hline`): \\
\begin{mytable}
  foo & This description is long. It is very long. It is more than one line long. It is automatically broken up into lines. \verb`\verb` works. \\
\end{mytable}
\end{document}

如何让我的环境自动在表格底部包含水平线?

我不介意切换tabularx到其他东西。我想同时使用内联和浮动环境。如果\verb不行的话会很烦人。目前,如果表格内的分页符不可能,那就没问题了,但随着表格越来越长,我可能不得不在某个时候解决这个问题。

附加问题:为什么每条水平线和下面的文本之间的空间这么小,以及如何使空间变得合适 - \strut

答案1

正如 tabularx 文档中所述,表单的主要限制\tabularx \endtabularx是它\endtabularx是最终代码中的第一个标记。因此,您看到的行为是记录在案的功能,而不是错误。

但是你可以这样做:

\documentclass{article}
\usepackage{array}
\usepackage{tabularx}
\makeatletter

\newenvironment{mytable}{%
  \let\savedtx\TX@endtabularx
  \def\TX@endtabularx{\toks@\expandafter{\the\toks@\\\hline}\savedtx}%
  \tabularx{\textwidth}{lX}
    \hline%
    Name & Description \\
    \hline%
}{%
  %\hline%
  \endtabularx%
}
\makeatother

\begin{document}
Manually (working fine): \\
\begin{tabularx}{\textwidth}{lX}
  \hline
  Name & Description \\
  \hline
  foo & This description is long. It is very long. It is more than one line long. It is automatically broken up into lines. \verb`\verb` works. \\
  \hline
\end{tabularx}

\medskip
Wrapper environment (error with the bottom \verb`\hline`): \\
\begin{mytable}
  foo & This description is long. It is very long. It is more than one line long. It is automatically broken up into lines. \verb`\verb` works.
\end{mytable}
\end{document}

相关内容