Is it possible to include graphics in lst-listing?
Yes, you can do this by escaping to LaTeX code within the listing. You just have to choose some character(s) not used in your code proper. Here, I've used the pipe (|
) as the escape character.
To get the background to appear properly, as discussed in Section 8.2 of the listings
package manual, you must input the listing from a file and surround it with your favorite framing environment. Here I've used mdframed
as shown in the manual. listings
' built-in background has gaps around the escaped content.
\begin{filecontents*}{my_r_code_test.r}
R code
@
|\includegraphics[width=0.5\textwidth]{example-image}|
\end{filecontents*}
\documentclass{article}
\usepackage{xcolor}
\usepackage{graphicx}
\usepackage{listings,mdframed}
\lstset{
language=R,
backgroundcolor=\color{black!5}, % set backgroundcolor
basicstyle=\footnotesize\ttfamily,% basic font setting
columns=fullflexible,
}
\begin{document}
Plain escapes (note gaps in background):
\begin{lstlisting}[escapeinside=||]
R code
@
|\includegraphics[width=0.5\textwidth]{example-image}|
\end{lstlisting}
With \verb|mdframed|:
\begin{mdframed}[backgroundcolor=black!5,linewidth=0pt,%
innerleftmargin=0pt,innertopmargin=0pt,innerbottommargin=0pt]
\lstinputlisting[escapeinside=||]{my_r_code_test.r}
\end{mdframed}
\end{document}
Yes, indeed, using escapeinside
, for example:
\begin{lstlisting}[escapeinside=`']
R code
@
`\includegraphics{example-image}'
\end{lstlisting}
Here's a complete MWE:
% arara: pdflatex
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\usepackage[scaled=.85]{beramono}
\usepackage{graphicx}
\lstset{
language=R,
backgroundcolor=\color{black!5}, % set backgroundcolor
basicstyle=\footnotesize\ttfamily,% basic font setting
columns=fullflexible,
}
\begin{document}
\begin{lstlisting}[escapeinside=`']
R code
@
`\includegraphics{example-image}'
\end{lstlisting}
\end{document}