lstlisting-environment 在 tabularx-environment 中不可用

lstlisting-environment 在 tabularx-environment 中不可用

请考虑以下示例。有人知道为什么我不能在 -environmentlistings中使用 -environmenttabularx吗?

\documentclass{article}
\usepackage[ngerman]{babel}

\usepackage{tabularx}
\usepackage{listings}

\usepackage{lipsum}

\begin{document}

\newenvironment{foo}{\tabularx{\textwidth}{p{2cm}X}}{\endtabularx}
\newcommand{\M}{\textit{Mathematica }}
\newcommand{\C}[1]{\texttt{#1}}

\newcommand{\LongText}{This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text. This is a long text.}

\lipsum[1-3]

\begin{tabularx}{\textwidth}{p{2cm}X}
Whatever & \LongText \LongText \\
Something else & \LongText \LongText \\
Code & \begin{lstlisting} for i=0 do... \end{lstlisting} 
\end{tabularx}


\end{document}

答案1

tabularx环境体被抓取作为宏参数,因此它可以在不同的宽度进行试验设置,listings是一种逐字风格的东西,而逐字风格的东西在宏参数中永远不起作用。

tabularx有一些代码可以实现这种\verb功能,但是任何更复杂的东西都注定会失败。

但是你可以这样做

\setbox0\vbox{\hsize5cm
\begin{lstlisting}
for i=0 do...
\end{lstlisting}}

\noindent\begin{tabularx}{\textwidth}{p{2cm}X}
Whatever & \LongText \LongText \\
Something else & \LongText \LongText \\
Code & \usebox0
\end{tabularx}

但是您必须提前知道您想要的宽度(或者做一些更复杂的事情,查询 tabularx 以获取宽度,然后在框中设置列表,然后再次执行 tabularx。注意,我\noindent在表格前面添加了,否则您会在 MWE 中收到过满框警告,因为全宽表格 + 段落缩进超过了全宽。

相关内容