列表中的行号被转义

列表中的行号被转义

在代码清单中使用带有转义符的文本颜色时,行号似乎有些不对。如果没有该escapeinside选项,一切都正常。我该如何解决这个问题?

数学家协会

\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}

结果是

输出

答案1

escapeinside 似乎添加了一些分组,并且代码不再能够正确设置“numberfirstline”的条件,并且测试失败。

您可以尝试更改定义,以便全局设置条件:

\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}

相关内容