8

I can't manage to let my text float around an listing. Assuming I have a text paragraph and I want the listing to be at the top right place with a certain width, and to be floated by the text.

\documentclass[letterpaper]{article}

\usepackage{listings}
\usepackage{blindtext}

\begin{document}

\blindtext

\begin{lstlisting} % this should be printed to the right of the text
public void Main (string[] args)
{
   // here goes some code
}
\end{lstlisting}

\end{document}

How can I do this?

Solution according to Guido's answer:

\begin{wrapfigure}[6]{r}{.6\textwidth}
\begin{minipage}{.6\textwidth}
\vspace{-2em}
\begin{lstlisting}
....
\end{lstlisting}
\end{minipage}
\end{wrapfigure}

With three modifications:

  • My listings produces captions with a box that is spanned over the whole textwidth, so I added a minipage.
  • The listing was a bit to far below, so I added a vspace.
  • The first optional parameter for wrapfigure specifies the number of lines the wrapfigure occupies (based on this answer: https://tex.stackexchange.com/a/285203/198066)
1

1 Answer 1

8

If I have understood correctly, you can use the wrapfig package (see textdoc wrapfig for the documentation).

\documentclass[letterpaper]{article}

\usepackage{listings}
\usepackage{blindtext}
\usepackage{wrapfig}

\begin{document}

\begin{wrapfigure}[5]{r}{.6\textwidth}
\begin{lstlisting} 
public void Main (string[] args)
{
   // here goes some code
}
\end{lstlisting}
\end{wrapfigure}

\blindtext
\end{document}

Producing enter image description here

3
  • exactly what I needed. Thanks! Is there also a better approach for the second point in my modifications? (see edited post)
    – Matthias
    Dec 8, 2012 at 21:51
  • Yes, you can use the aboveskip option of listings, e.g., \begin{listings}[aboveskip=-3pt]
    – Guido
    Dec 8, 2012 at 22:10
  • Is it possible to set the width of the wrapfigure automatically based on the max length of the code in the listing?
    – SOFe
    Nov 26, 2020 at 2:14

You must log in to answer this question.

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