133

I have a java lstlisting and it is too big and does not mach a single page.

Is there any way to specify font for specific listing, not all listings in document?

2 Answers 2

168

You can set the option directly with the lstlisting environment option basicstyle

\documentclass{article}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[
    basicstyle=\tiny, %or \small or \footnotesize etc.
]
int isJava = 1;
\end{lstlisting}
\end{document}

See also this answer

3
  • 6
    I really like this approach, but one needs to remember that other attributes of basicstyle (such as the font colour), will be lost when the size is changed this way.
    – user4417
    Nov 22, 2018 at 11:40
  • 8
    Actually, the colours seem to stay the same, but one needs to specify \ttfamily as well so as not to lose monospace font.
    – oarfish
    Jan 7, 2019 at 14:19
  • This really isn't a good solution, as it breaks carefully designed styles. As some others comment here, one can adjust things locally as well, but this is brittle for large documents. If you change the global style later, you might not remember to make fixes for the customized listing. There is hopefully a better way ... May 16, 2020 at 8:55
31

The best way to do this is by using the lstdefinestyle functionality which is built into the listings package. Encapsulate your style as follows (I've used a crummy MATLAB style definition as an example):

\lstdefinestyle{myCustomMatlabStyle}{
  language=Matlab,
  numbers=left,
  stepnumber=1,
  numbersep=10pt,
  tabsize=4,
  showspaces=false,
  showstringspaces=false
}

Then, use it like so:

% A "large" listing
\lstset{basicstyle=\large,style=myCustomMatlabStyle}

\begin{lstlisting}
...
\end{lstlisting}

% A "tiny" listing
\lstset{basicstyle=\tiny,style=myCustomMatlabStyle}

\begin{lstlisting}
...
\end{lstlisting}

The results of the two different lstlisting's will be different sizes, as set by your basicstyle command.

If you do not want to set the style globally with \lstset, you can also set the style only for a specific lstlisting:

\begin{lstlisting}[style=myCustomMatlabStyle]
...
\end{lstlisting}

or even set all properties in the lstlisting, without defining a style:

\begin{lstlisting}[language=Matlab,
                   numbers=left,
                   stepnumber=1,
                   numbersep=10pt,
                   tabsize=4,
                   showspaces=false,
                   showstringspaces=false]
...
\end{lstlisting}
1
  • 7
    Be careful with \lstset, though; its effects are global.
    – jub0bs
    May 25, 2014 at 8:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .