Syntax highlighting of numeric literals with the listings package

listingssyntax highlighting

I'm working on a document that contains a lot of python code snippets, many of which have numeric literals in them. For example, something like:

var_a = 3
var_b = 20000
var_c = 1.75e12
var_d = 0.1415

would be common to see in this document. Notice that StackExchange's syntax highlighting renders the numeric values in orange. I'm trying to get listings to reproduce this behavior. I have a style declaration which looks something like:

\lstdefinestyle{mystyle}{
    language=python,
    alsoletter={1234567890},
    emph={1,2,3,4,5,6,7,8,9,0},
    emphstyle=\color{orange}
}

This seems to almost work. I correctly get single-digit numbers highlighted in orange, but multi-digit numbers are not (and of course neither are floating point numbers or numbers in scientific notation). So in my example snippet above, only the first line would be correctly highlighted.

Is it possible to get listings to highlight numbers in a way that behaves more as expected? I would even be happy if it's possible to just get this to work with integers with more than one digit if floats and scientific notation aren't possible.

Best Answer

Try this code. Its a very simplified solution. See the links mentioned in the comments and also Changing the color of numbers and special words for more comprehensive solutions.

b

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor} 

\renewcommand{\lstlistingname}{Phyton code}

\lstdefinestyle{mystyle}{
    language=Python,            
    captionpos=b,             
}   

\lstset{style=mystyle}

\newcommand\digitstyle{\textcolor{orange}}
    {0}{{{\digitstyle0}}}1
    {1}{{{\digitstyle1}}}1
    {2}{{{\digitstyle2}}}1
    {3}{{{\digitstyle3}}}1
    {4}{{{\digitstyle4}}}1
    {5}{{{\digitstyle5}}}1
    {6}{{{\digitstyle6}}}1
    {7}{{{\digitstyle7}}}1
    {8}{{{\digitstyle8}}}1
    {9}{{{\digitstyle9}}}1
    {.}{{{\digitstyle.}}}1
}


\begin{document}
    
    \begin{lstlisting}[language=Python, caption=Highlighting  numeric literals.]    
        var_a = 3
        var_b = 20000
        var_c = 1.75e12
        var_d = 0.1415      
    \end{lstlisting}    

\end{document}
Related Question