Margin notes in listing with float environment – Error: Float(s) lost

Based on this question: Margin notes in listing with float environment – Error: Float(s) lost I have now other question. The solution is working fine.

But I want to use floats for listings, to prevent page breaks inside the code (~ 30 lines). By using floats I get an error:

 ! LaTeX Error: Float(s) lost.

\documentclass{article}

\usepackage{listings}
%\usepackage{marginnote}

\begin{document}

\lstset{language=C++,numbers=left,escapeinside={(*@}{@*)}, float, floatplacement=H}

\begin{lstlisting}
for (int i = 0; i < 10; i++)
{
cout << i << endl;
}
\end{lstlisting}

\begin{lstlisting}
for (int i = 0; i < 10; i++)
{
cout << i << endl;(*@\marginpar{margin note}@*)
}
\end{lstlisting}

%% I've tried to wrap \marginnote with boxes, but could't fix it.

\begin{lstlisting}
for (int i = 0; i < 10; i++)
{
cout << i << endl;(*@\marginpar{margin note}@*)
}
\end{lstlisting}


By setting listing in minipage environment does not solve the problem.

• Please help us help you and add a minimal working example (MWE) that illustrates your problem. Reproducing the problem and finding out what the issue is will be much easier when we see compilable code, starting with \documentclass{...} and ending with \end{document}. – user31729 Jul 22 '15 at 9:01
• It was the same as in ohter question with float difference. – frankenstein Jul 22 '15 at 9:21
• you cannot have flosts inside floats. \marginpar is a type of float. – daleif Jul 22 '15 at 9:28
• But what should be then the solution for the problem described in referenced post? If i use float environment and \marginnote that building fine, but with the problem described in other post. And \marginpar render it well. – frankenstein Jul 22 '15 at 9:40

You cannot nest floating environments; \marginpar's are floats. You can define a command to mimic a marginpar by making it non-floating and invisible:

\documentclass{article}

\usepackage{listings,calc}
\lstset{language=C++,numbers=left,escapeinside={(*@}{@*)}}

\newcommand*{\marginnote}[1]{%
\makebox[0pt][l]{%
\makebox[\linewidth+\marginparsep][l]{}%
\parbox[t][0pt][t]{1\marginparwidth}{#1}%
}%
}

\usepackage[showframe]{geometry}

\begin{document}

\begin{lstlisting}[float, floatplacement=t]
for (int i = 0; i < 10; i++)
{
(*@\marginnote{margin note}@*)cout << i << endl;
}
\end{lstlisting}

\noindent\mbox{}

\begin{lstlisting}[float, floatplacement=h]
for (int i = 0; i < 10; i++)
{
(*@\marginnote{margin\\ note}@*)    cout << i << endl;
}
\end{lstlisting}
\end{document}