如何在 lstlisting 包中的 emph 中添加 #?

如何在 lstlisting 包中的 emph 中添加 #?

我当前的 lstlisting 包格式如下所示。我不知道为什么,但 # 没有显示为蓝色,而是显示为金色。我希望将其显示为 emphstyle 中指定的颜色。

\documentclass{article}

\usepackage[a4paper,width=150mm,top=25mm,bottom=25mm]{geometry}
\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\definecolor{golden}{rgb}{0.83, 0.53, 0.06}
\definecolor{MyBlue}{rgb}{0.18, 0.3, 0.5}

\lstset{frame=tb,
  language=C++,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=none,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{golden},
  commentstyle=\color{dkgreen},
  stringstyle=\color{dkgreen},
  breaklines=true,
  breakatwhitespace=true,
  tabsize=3,
  emph = {\texttt{\#}, ifndef, define, include, RECEIVER_H, SENDER_H, RECEIVERTHREAD_H, SENDERTHREAD_H, HANDLER_H, SHAPES_H},
  emphstyle = {\color{MyBlue}},
  morekeywords = {},
  escapechar={|}
}


\begin{document}
\begin{lstlisting}
#ifndef SHAPES_H
#define SHAPES_H

#include |\color{dkgreen}<QPoint>|
#include |\color{dkgreen}<QRect>|
#include |\color{dkgreen}<QPainterPath>|
#include |\color{dkgreen}<QList>|
#include |\color{dkgreen}<QPolygon>|
#include |\color{dkgreen}<QtMath>|
\end{lstlisting}
\end{document}

输出如下所示:

在此处输入图片描述

答案1

添加#带有 的字符literate。(我没有得到金色,只是从您的 MWE 中得到了黑色)

A

% !TeX TS-program = pdflatex

\documentclass{article}

\usepackage[a4paper,width=150mm,top=25mm,bottom=25mm]{geometry}
\usepackage{listings}
\usepackage{xcolor}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\definecolor{golden}{rgb}{0.83, 0.53, 0.06}
\definecolor{MyBlue}{rgb}{0.18, 0.3, 0.5}

\lstset{frame=tb,
    language=C++,
    aboveskip=3mm,
    belowskip=3mm,
    showstringspaces=false,
    columns=flexible,
    basicstyle={\small\ttfamily},
    numbers=none,
    numberstyle=\tiny\color{gray},
    keywordstyle=\color{golden},
    commentstyle=\color{dkgreen},
    stringstyle=\color{dkgreen},
    breaklines=true,
    breakatwhitespace=true,
    tabsize=3,
    emph = {ifndef, define, include, RECEIVER_H, SENDER_H, RECEIVERTHREAD_H, SENDERTHREAD_H, HANDLER_H, SHAPES_H},
    emphstyle = {\color{MyBlue}},
    morekeywords = {},
    literate=*%  added <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    {\#}{{\textcolor{MyBlue}{\#}}}{1},
    escapechar={|}
}

\begin{document}
    \begin{lstlisting}
        #ifndef SHAPES_H
        #define SHAPES_H        
        #include |\color{dkgreen}<QPoint>|
        #include |\color{dkgreen}<QRect>|
        #include |\color{dkgreen}<QPainterPath>|
        #include |\color{dkgreen}<QList>|
        #include |\color{dkgreen}<QPolygon>|
        #include |\color{dkgreen}<QtMath>|
    \end{lstlisting}
\end{document}

相关内容