背景
我尝试新建一个环境来显示 LaTeX 代码和编译结果。我参考了siunitx.tex并作出了如下的 MWE:
\documentclass{article}
% For creating code demonstrations
% This needs access to some code-level interfaces in listings
\usepackage{listings}
\makeatletter
\lst@RequireAspects{writefile}
\newsavebox\LaTeXdemo@box
\lstnewenvironment{LaTeXdemo}[1][code and example]
{%
\global\let\lst@intname\@empty
\edef\LaTeXdemo@end{%
\expandafter\noexpand\csname LaTeXdemo@@#1@end\endcsname
}%
\@nameuse{LaTeXdemo@@#1}%
}
{\LaTeXdemo@end}
\ExplSyntaxOff
\newcommand\LaTeXdemo@new[3]{%
\@namedef{LaTeXdemo@@#1}{#2}%
\@namedef{LaTeXdemo@@#1@end}{#3}%
}
\newcommand*\LaTeXdemo@common{%
\setkeys{lst}
{%
basicstyle = \ttfamily\small,
basewidth = 0.51em,
backgroundcolor = \color{cyan!10},
% rulecolor = \color{red!10},
frame = shadowbox,
frameround = tttt,
% framerule = 0pt,
gobble = 4,
tabsize = 2,
numbers = left,
language = [LaTeX]TeX,
% linewidth = 0.5\linewidth
}%
}
\newcount\LaTeXdemo@count
\newcommand*\LaTeXdemo@input{%
\catcode`\^^M = 10\relax
\input{\jobname-\number\[email protected]}%
}
\LaTeXdemo@new{code and example}{%
\setbox\LaTeXdemo@box=\hbox\bgroup
\global\advance\LaTeXdemo@count by 1 %
\lst@BeginAlsoWriteFile{\jobname-\number\[email protected]}%
\LaTeXdemo@common
}{%
\lst@EndWriteFile
\egroup
\begin{center}
\ifdim\wd\LaTeXdemo@box > 0.48\linewidth
\begin{minipage}{\linewidth}
\usebox\LaTeXdemo@box
\end{minipage}%
\par
\begin{minipage}{\linewidth}
\LaTeXdemo@input
\end{minipage}
\else
\begin{minipage}{0.48\linewidth}
\LaTeXdemo@input
\end{minipage}%
\hfil
\begin{minipage}{0.48\linewidth}
\usebox\LaTeXdemo@box
\end{minipage}%
\fi
\end{center}
}
\LaTeXdemo@new{code and float}{%
\global\advance\LaTeXdemo@count by 1 %
\lst@BeginAlsoWriteFile{\jobname-\number\[email protected]}%
\LaTeXdemo@common
}{%
\lst@EndWriteFile
\LaTeXdemo@input
}
\LaTeXdemo@new{code only}{\LaTeXdemo@common}{}
\makeatother
\begin{document}
\begin{LaTeXdemo}
\begin{enumerate}
\item 1
\item 2
\item 3
\item 4
\item 5
\end{enumerate}
\end{LaTeXdemo}
\end{document}
问题
MWE 效果很好。但当我想给代码部分上色时,我发现它太长了:
于是我用 来linewidth
调整它。然后我想:为什么不自己计算宽度呢?然后我想像往常一样使用 LaTeX3 来计算宽度。
但是!问题是:
lstnewenvironment
就像newenvironment
:代码不包含该BODY
部分environ
,所以我无法测量宽度。
那么有什么方法可以获取 的主体吗lstnewenvironment
?然后我可以将其存储到框中并获取其宽度。
问题摘要
感谢@user202729 提醒我\LaTeXdemo@box
包含内容,我确实测量了宽度,但是我无法设置宽度,似乎内容已经固定了,虽然我得到了它的宽度,但 lstset 根本没有影响它。