# Automatically resize lstlisting fontsize in a beamer slide

I have frames of the following format (code followed by an itemize):

\begin{frame}[fragile]
\frametitle{Blah}
\begin{lstlisting}
Five to seven lines of code here...
\end{lstlisting}
\begin{itemize}
\item explanation
\item explanation
\item explanation
\end{itemize}
\end{frame}


What I want to accomplish is for the lstlisting to automatically resize the font to take up as much space as possible without causing horizontal and vertical overflows.

First of all: beamer does not provide any automatic scaling of text or diagrams like MS Power Point, because its author thinks that it leads to bad presentations. If the material doesn't fit on one slide unscaled simply make two or more slides out of it.

Adjusting the font or scaling some listings a little bit might be still OK, but I wouldn't do it automatically. Just because the whole slide is filled out doesn't make it automatically look good.

You should manually adjust the size either by adjusting the font size using basicstyle=<some font size command> (e.g. \small, \scriptsize, ...) in the optional argument of the lstlisting environment or by scaling the whole listing. Some people don't like scaling text freely, but I personally would say it is OK in this case. The normal scaling macro \scalebox{<factor>}{...} from the graphics package doesn't work with verbatim content. You need to either store it in a box register e.g. using the lrbox environment or use the adjustbox package which provides some extended box macros and environment on top of the ones provided by graphicx. The adjustbox environment accepts verbatim content and takes all options of \includegraphics including scale and height,width,keepsaspectratio.

I would adjust the height manually. You could try to adjust the solutions to How to define a figure size so that it consumes the rest of a page? so that the amount is calculated automatically. However with an figure or listing in the middle of the text it is much more difficult than with one at the end.

\documentclass{beamer}

\usepackage{listings}

\begin{document}

\newlength\someheight
\setlength\someheight{3cm}

\begin{frame}[fragile]
\frametitle{Blah}
\begin{lstlisting}
function example () {
if (example) {
print "Example";
}
else {
print "Automatic Scaling in Presentations is evil anyway";
}
}
\end{lstlisting}