Search code examples
latexlistings

Different colors for different keywords in listing environment doesn't work


I've read in several answers that I can use [number] to set different colors for different keywords in a listings environment. However, when I try it this way it doesn't work.

These are my preamble and a small example script:

\usepackage{listings}
\usepackage{color}
\usepackage[dvipsnames]{xcolor}

\definecolor{gray}{rgb}{0.95,0.95,0.95}
\definecolor{Green}{rgb}{0.1,0.69,0.1}
\renewcommand{\lstlistingname}{Codice}

\lstdefinelanguage{Python}
{
  keywords={from, import, def, return, as, for, if, in, len},
  keywordstyle=\color{Green},
  keywords=[2]{centers}
  keywordstyle=[2]{blue} 
  morecomment=[l]{\#},
  morestring=[b]",
  alsodigit={-},
  alsoletter={&}
}
    
\lstdefinestyle{custompython}{
    language=Python,
    frame=tlrb,
    aboveskip=3mm,
    belowskip=5mm,
    backgroundcolor=\color{gray},
    showstringspaces=true,
    columns=flexible,
    basicstyle={\small\ttfamily},
    numbers=left,
    numberstyle=\tiny\color{orange}\ttfamily,
    numbersep=5pt,
    commentstyle=\color{orange},
    stringstyle=\color{purple},
    commentstyle=\small\color{red}\ttfamily,
    breaklines=false,
    breakatwhitespace=true
    tabsize=5
}

\begin{lstlisting}[firstnumber=1,language=Python, style=custompython]

from pyLensLib.maputils import map_obj, contour_fit

def getImageEllipticity( img, fsize, f=0.05):
 
    m, cnt = map_obj(img), m.get_contours(lev=f)
    centers, axesList = [], []
    
    return centers
\end{lstlisting}

Solution

  • A very good answer was already given by user Symbol 1. Example language is in C++, but the way to style your code is the same:

    Other keywords and symbols highlighting with lstlisting

    \documentclass[10pt,a4paper]{scrartcl}
    
    
    \usepackage{xcolor}
    \definecolor{main-color}{rgb}{0.6627, 0.7176, 0.7764}
    \definecolor{back-color}{rgb}{0.1686, 0.1686, 0.1686}
    \definecolor{string-color}{rgb}{0.3333, 0.5254, 0.345}
    \definecolor{key-color}{rgb}{0.8, 0.47, 0.196}
    
    \usepackage{listings}
    
    
    
    \lstdefinestyle{mystyle}
    {
        language = C++,
        basicstyle = {\ttfamily \color{main-color}},
        backgroundcolor = {\color{back-color}},
        stringstyle = {\color{string-color}},
        keywordstyle = {\color{key-color}},
        keywordstyle = [2]{\color{lime}},
        keywordstyle = [3]{\color{yellow}},
        keywordstyle = [4]{\color{teal}},
        otherkeywords = {;,<<,>>,++},
        morekeywords = [2]{;},
        morekeywords = [3]{<<, >>},
        morekeywords = [4]{++},
    }
    
    \begin{document}
    \begin{lstlisting}[firstnumber=1,language=C++, style=mystyle]
    
    #include <iostream>
    
    using namespace std;
    
    int x = 2;
    
    //comment
    for (int i = 0; i < x; ++i) {
        cout << "stand_alone_complex" << endl;
    }
    
    \end{lstlisting}
    \end{document}