2

I want to write C++ code in LaTeX using the listings package. The problem is that I want to change the color numbers in code (integers, doubles...). The only solution I found was this:

\lstdefinestyle{customc}{
    belowcaptionskip=1\baselineskip,
    breaklines=true,
    frame=L,
    xleftmargin=\parindent,
    showstringspaces=false,
    basicstyle=\footnotesize\ttfamily,
    language=C++,
    morekeywords={Mat, cvtColor,one},
    keywordstyle=\bfseries\color{green!40!black},
    commentstyle=\itshape\color{purple!40!black},
    stringstyle=\color{orange},
 }
\lstset{literate=%
    {0}{{{\color{red}0}}}1
    {1}{{{\color{red}1}}}1
    {2}{{{\color{red}2}}}1
    {3}{{{\color{red}3}}}1
    {4}{{{\color{red}4}}}1
    {5}{{{\color{red}5}}}1
    {6}{{{\color{red}6}}}1
    {7}{{{\color{red}7}}}1
    {8}{{{\color{red}8}}}1
    {9}{{{\color{red}9}}}1
}

But this solution give me this:

result code

Some numbers in variables are put in color too, but I don't want this. Someone knows another form of putting different color number in code?

2

I know only some tricky code with escaping the digits:

\documentclass{report}
\usepackage{listings}
\usepackage{xcolor}
\lstdefinestyle{customc}{
    belowcaptionskip=1\baselineskip,
    breaklines=true,
    frame=L,
    xleftmargin=\parindent,
    showstringspaces=false,
    basicstyle=\footnotesize\ttfamily,
    language=C++,
    morekeywords={Mat, cvtColor,one},
    keywordstyle=\bfseries\color{green!40!black},
    commentstyle=\itshape\color{purple!40!black},
    stringstyle=\color{orange},
    escapechar=\%,
}
\def\N#1{\textcolor{red}{#1}}
\begin{document}

\begin{lstlisting}[style=customc]
area = moment.m00
Point2f(x,y), %\N1%, %\N1,% 
\end{lstlisting}

\begingroup
\catcode`\0=13 \def0{\textcolor{red}{\string0}}
\catcode`\1=13 \def1{\textcolor{red}{\string1}}
\begin{lstlisting}[style=customc]
area = moment.m00
Point2f(x,y), %1%, %1%, %0%,  
\end{lstlisting}
\endgroup

\end{document}

enter image description here

1
  • @Red_Cloud Ok it could be a solution but it's very convoluted I mean there must be another easier way. Maybe another package like minted or other. – Rafa Hernández May 22 '19 at 11:16

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.