我正在listings
将 Java 代码放入我的beamer
幻灯片中。
有时,我想为代码添加框架,但又不想让框架占据整个页面的宽度。我希望框架只占据代码的宽度,而不再占更多。
有没有办法做到这一点?
答案1
这是一个带有 的解决方案fancyvrb
,并带有 的输出listings
:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{beramono}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage{fancyvrb}
\usepackage{listings}
\makeatletter
\newenvironment{SmallListing}[1][]
{\lstset{#1}\VerbatimEnvironment\begin{VerbatimOut}{VerbEnv.tmp}}
{\end{VerbatimOut}\settowidth\@tempdima{%
\lstinputlisting{VerbEnv.tmp}}
\minipage{\@tempdima}\lstinputlisting{VerbEnv.tmp}\endminipage}
\makeatother
\begin{document}
\blindtext
\begin{center}
\begin{SmallListing}
[language=Java,frame=single,columns=fixed,
basicstyle=\small\ttfamily,
keywordstyle=\bfseries]
static void main () {
int foo;
string baz;
}
\end{SmallListing}
\end{center}
\end{document}
答案2
这varwidth
包裹提供varwidth
与 类似的环境minipage
。但是,如果内容达到指定的最大值,它会将其内容放入“自然”宽度的框中:
\usepackage{varwidth}% http://ctan.org/pkg/varwidth
...
\begin{varwidth}{0.5\textwidth}
...
\end{varwidth}
使用的问题listings
包裹是,因为@尼尔提到,它希望占据整个\textwidth
。lstlisting
还有其他替代方案,例如algorithmicx
包:
\documentclass{article}
\usepackage{varwidth}% http://ctan.org/pkg/varwidth
\usepackage{algorithmicx}% http://ctan.org/pkg/algorithmicx
\begin{document}
\centering
\fbox{\begin{varwidth}{0.7\textwidth}
\begin{algorithmic}[1]
\State Here is some code
\State Some lines or very long compared to others
\State Some are short.
\end{algorithmic}
\end{varwidth}}
\end{document}
答案3
考虑将lstlisting
环境置于minipage
:
\begin{center}% if you want
\begin{minipage}{0.5\textwidth}
\begin{lstlisting}[...]
but don't indent your source code
unless you want extra white-space
on the left side of your listing!
\end{lstlisting}
\end{minipage}
\end{center}
编辑后添加:使用fancyvrb
,我找到了一个非常笨拙的解决方案,但它却给出了所需的输出。
\documentclass{article}
\usepackage{fancyvrb,listings}
\begin{document}
% The following saves the code in a separate file.
\begin{VerbatimOut}{\jobname.listing}
\begin{lstlisting}[frame=single]
but don't indent your source code
unless you want extra white-space
on the left side of your listing!
\end{lstlisting}
\end{VerbatimOut}
% The following somehow manages to find the natural width of the code!
\newlength\codewidth
\settowidth\codewidth{\input{\jobname.listing}}
% Make a minipage with the natural width of the code.
\noindent
\begin{minipage}{\codewidth}%
\input{\jobname.listing}%
\end{minipage}
\end{document}
我们能否整理一下,让这个机制在包装器环境中被捕获lstlisting
?