问题陈述

问题陈述

问题陈述

我使用的自定义文档类过度使用了相对较宽的外边距。为了增强眼睛对主文本块和边距的判断,我想自动将所有表格排版为两种宽度之一

  • 如果表格数据所需空间比主文本块小,则表格宽度应该与主文本块的宽度相同,即\textwidth
  • 或者,如果表格数据需要的空间比主文本块更多,则表格宽度应等于主文本块的宽度加上边距加上两者之间的任何空格,即\textwidth++\marginparwidth\marginparsep

我所想象的定制环境是什么样的

想法是编写一个新的 LaTeX 环境autotable下面调用),我将表格数据传递给它,然后它将在自动选择的表格宽度上“均匀分布”(见下文)该数据。

\begin{autotable}% Imaginary macro that automatically determines applicable table width
  \begin{tabular}{lll}% Or some alternative command from another package?
    Foo & Bla & Moo & Ma\\
    Ma  & Bla & Foo & Ha
  \end{tabular}
\end{autotable}

我正在寻找这种自定义 LaTeX 环境的实现,如果tabularx需要,可以使用额外的软件包。它需要的参数越少(如果有的话),越好。

这种定制环境必须解决的问题

  • 出现的一个问题是,在这种情况下“均匀分布”的确切含义是什么。相关问题的答案似乎在这方面提供了一个很好的解决方案,因为它在视觉上强调了主文本块的左右边框,这正是我想要的。
  • 另一个问题是如何确定表格数据是否“舒适地适合”主文本块,或者是否需要使用边距。在这里,我将非常感激指点。

答案1

扩展 David 对所提问题的处理方法(自动拉伸表格以均匀填充水平空间?)。

该语法使用指定的列\autotable{columns}content\endautotable将内容放入临时框中(请参阅tabular附录为环境形式的解决方案)。如果尺寸过小,则使用 David 的方法,并将尺寸设置为\textwidth。如果尺寸过大,则使用 David 的方法,并将尺寸设置为较大。

我没有在宏前面和后面加上\pars,但这样做可能是明智的,因为看起来 OP 永远不会将它与其他文本或内容合并在一行上。

\documentclass{article}
\usepackage{tabularx}
\usepackage{showframe,lipsum}
\def\autotable#1#2\endautotable{\noindent%
  \setbox0=\hbox{\begin{tabular}{#1}#2\end{tabular}}%
  \ifdim\wd0>\textwidth\relax%
    \begin{tabular*}{\dimexpr\textwidth+\marginparwidth+\marginparsep\relax}%
      {@{\extracolsep{\stretch{1}}}#1@{}}#2\end{tabular*}%
  \else%
    \begin{tabular*}{\textwidth}{@{\extracolsep{\stretch{1}}}#1@{}}#2\end{tabular*}%
  \fi%
}
\parskip 1ex
\begin{document}

\lipsum[1]

\autotable{llll}
    Foo & Bla & Moo & Ma\\
    Ma  & Bla & Foo & Ha
\endautotable

\lipsum[2]

\autotable{llll}
    Foo Foo Foo Foo Foo Foo Foo & Bla Bla Bla Bla & Moo Moo Moo Moo & Ma\\
    Ma  & Bla & Foo & Ha
\endautotable

\lipsum[3]
\end{document}

在此处输入图片描述


附录

OP 要求以环境形式提供解决方案。这就是使用environ包的解决方案。

\documentclass{article}
\usepackage{tabularx,environ}
\usepackage{showframe,lipsum}
\NewEnviron{autotable}[1]{\noindent%
  \setbox0=\hbox{\begin{tabular}{#1}\BODY\end{tabular}}%
  \ifdim\wd0>\textwidth\relax%
    \begin{tabular*}{\dimexpr\textwidth+\marginparwidth+\marginparsep\relax}%
      {@{\extracolsep{\stretch{1}}}#1@{}}\BODY\end{tabular*}%
  \else%
    \begin{tabular*}{\textwidth}{@{\extracolsep{\stretch{1}}}#1@{}}\BODY\end{tabular*}%
  \fi%
}
\parskip 1ex
\begin{document}

\lipsum[1]

\begin{autotable}{llll}
    Foo & Bla & Moo & Ma\\
    Ma  & Bla & Foo & Ha
\end{autotable}

\lipsum[2]

\begin{autotable}{llll}
    Foo Foo Foo Foo Foo Foo Foo & Bla Bla Bla Bla & Moo Moo Moo Moo & Ma\\
    Ma  & Bla & Foo & Ha
\end{autotable}

\lipsum[3]
\end{document}

相关内容