# Broken line numbers in listing with escapes

When using some text colors with escapes inside a code listing, the line numbers seem to be somehow off. Without the escapeinside option, everything works fine. How can I fix this?

The MWE

\documentclass[border=7mm,varwidth]{standalone}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{xcolor}

\usepackage{listings}
\lstset{%
showspaces=false,
showstringspaces=false,
breaklines=true,
frame=single,
keepspaces=true,
basicstyle=\footnotesize\ttfamily,
numbers=left,
stepnumber=5,
firstnumber=1,
numberfirstline=true,
}

\begin{document}

\begin{lstlisting}[escapeinside={<@}{@>}]
public class MyApplication {

public static void main(String[] args) {
<@\textcolor{blue}{\ttfamily doSomething();}@>
<@\textcolor{blue}{\ttfamily System.out.println("Finished");}@>
}
}
\end{lstlisting}

\end{document}


results in

The escapeinside seems to add some grouping and the code no longer can set the conditional for "numberfirstline" correctly and the test fails.

You can try to change the definition so that the conditional is set globaly:

\documentclass[border=7mm,varwidth]{standalone}

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[ngerman]{babel}
\usepackage{xcolor}

\usepackage{listings}
\lstset{%
showspaces=false,
showstringspaces=false,
breaklines=true,
frame=single,
keepspaces=true,
basicstyle=\footnotesize\ttfamily,
numbers=left,
stepnumber=5,
firstnumber=1,
numberfirstline=true,
}
\makeatletter
\gdef\lst@numberfirstlinefalse{\global\let\lst@ifnumberfirstline\iffalse}
\makeatother

\begin{document}

\begin{lstlisting}[escapeinside={<@}{@>}]
public class MyApplication {

public static void main(String[] args) {
<@\textcolor{blue}{\ttfamily doSomething();}@>
<@\textcolor{blue}{\ttfamily System.out.println("Finished");}@>
}
}
\end{lstlisting}

\end{document}

• This works as long as I only have one listing per document. Adding a second listing (for example by copying the existing one) does not put a number in front of the first line of the second listing anymore. Can this be fixed as well? Jul 12 '18 at 12:16
• You can reuse numberfirstline=true in the options of the following listings. Or define a lstenvironment which issues the key always. Jul 12 '18 at 12:22