2

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

output

2

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? – epR8GaYuh Jul 12 '18 at 12:16
  • 1
    You can reuse numberfirstline=true in the options of the following listings. Or define a lstenvironment which issues the key always. – Ulrike Fischer Jul 12 '18 at 12:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.