[Tex/LaTex] How to color digits with the listings package

colorformattinglistings

For my project, I've been using the listings package in order to color the keywords, comments, strings, and digits in the code.

The thing is, I've managed to color the keywords, comments and strings, however, I couldn't color the digits within the code without coloring those in the comments/strings.

I've tried using the solution proposed in Coloring digits with the listings package; however, it didn't work. The digits weren't colored in the strings, but they were in the comments.

Would you be kind to suggest me a solution?

Best Answer

Based on “Listings package: How can I format all numbers?” I build this code

\documentclass{minimal}
\usepackage{listings}
\usepackage{xcolor}

\newcommand{\textcolordummy}[2]{#2}

\lstset{
    language=TeX,
    commentstyle={\color{green}\let\textcolor\textcolordummy},
}

\lstdefinestyle{FormattedNumber}{%
    literate={0}{{\textcolor{blue}{0}}}{1}%
             {1}{{\textcolor{blue}{1}}}{1}%
             {2}{{\textcolor{blue}{2}}}{1}%
             {3}{{\textcolor{blue}{3}}}{1}%
             {4}{{\textcolor{blue}{4}}}{1}%
             {5}{{\textcolor{blue}{5}}}{1}%
             {6}{{\textcolor{blue}{6}}}{1}%
             {7}{{\textcolor{blue}{7}}}{1}%
             {8}{{\textcolor{blue}{8}}}{1}%
             {9}{{\textcolor{blue}{9}}}{1}%
             {.0}{{\textcolor{blue}{.0}}}{2}% Following is to ensure that only periods
             {.1}{{\textcolor{blue}{.1}}}{2}% followed by a digit are changed.
             {.2}{{\textcolor{blue}{.2}}}{2}%
             {.3}{{\textcolor{blue}{.3}}}{2}%
             {.4}{{\textcolor{blue}{.4}}}{2}%
             {.5}{{\textcolor{blue}{.5}}}{2}%
             {.6}{{\textcolor{blue}{.6}}}{2}%
             {.7}{{\textcolor{blue}{.7}}}{2}%
             {.8}{{\textcolor{blue}{.8}}}{2}%
             {.9}{{\textcolor{blue}{.9}}}{2}%
             ,
   basicstyle=\ttfamily,%  Optional to use this
}

\begin{document}

\begin{lstlisting}[style=FormattedNumber]
Text ... 123 4.5 % 123 comment
123
\end{lstlisting}
\end{document}

The trick is to let the commentstyle disable the \textcolor command.

result