Scaling inline code to the current font size

Package listings has too hooks TextStyle and DisplayStyle or a switch \lst@ifdisplaystyle, which can be used for your purpose to set a different font size in inline and displayed code listings, e.g.:

\documentclass{article}
\usepackage{color}
\usepackage{listings}

\makeatletter
\lstdefinestyle{mystyle}{
  basicstyle=%
    \ttfamily
    \color{blue}%
    \lst@ifdisplaystyle\scriptsize\fi
}
\makeatother

\lstset{style=mystyle}

\begin{document}
\Large
\noindent
Here is a very important keyword: \lstinline|foo|.
\begin{lstlisting}
Some code with foo.
\end{lstlisting}
\end{document}

Result


@HeikoOberdiek's explanation to his answer above undersells its power and indeed, based solely on his explanation, you wouldn't think that his answer fully solved the OP's problem (as one commenter objected).

Heiko's claim is only that he provided a method to "to set a different font size in inline and displayed code listings." But what the OP wanted was that \lstinline would inherit the font size of the surrounding text. Heiko's solution does do that, though it won't be clear to readers that it does.

For that reason, I just want to provide an example showing that indeed, with Heiko's solution, the \lstinline font size does grow and shrink to adjust to the surrounding text. (If Heiko would like to add a similar example to his answer, I'd gladly delete this one.)

I add a \texttt{foo} directly after each \lstinline|foo| just to facilitate a comparison of the heights of the two foos.

enter image description here

\documentclass{article}
\usepackage{color}
\usepackage{listings}

\makeatletter
\lstdefinestyle{mystyle}{
  basicstyle=%
    \ttfamily
    \color{blue}%
    \lst@ifdisplaystyle\footnotesize\fi
}
\makeatother

\lstset{style=mystyle}

\begin{document}
\title{Here is a title with \lstinline|foo| \texttt{foo}.}
\date{}
\maketitle
\section{Here is a section heading with \lstinline|foo| \texttt{foo}.}
\Large
Here is: \lstinline|foo| \texttt{foo}.\\
\Huge
Here is: \lstinline|foo| \texttt{foo}.\\
\begin{lstlisting}
Some code with foo.
\end{lstlisting}
\end{document}

Tags:

Listings