[Tex/LaTex] Keyword Highlighting not working in Python with listings

listingssyntax highlighting

I am unable to get keywords to be highlighted in typeset Python.

Latex source:

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

\lstset{
language=Python,
frame=single,
numbers=left,
showspaces=false,
showstringspaces=false,
basicstyle=\ttfamily,
captionpos=t,
caption=\lstname
keywordstyle=\ttfamily \color{blue},
keywordstyle=[2]\ttfamily \color{blue},
stringstyle=\color{green}\ttfamily,
commentstyle=\color{red}\ttfamily
}

\begin{document}

Keywords are not highlighted properly in the below segment:

\begin{lstlisting}
# This is a comment
print("Latex keywordstyles not working?")
if this_is_highlighted:
    print("Yay, this works!")
else:
    print("Why isn't this working?")
\end{lstlisting}
\end{document}

Typeset output:

Output

Why isn't the keywordstyle coloring working when the keywords are properly defined in lstlang1.sty?

Best Answer

Try this:

% My standard header for TeX.SX answers:
\documentclass[a4paper]{article} % To avoid confusion, let us explicitly 
                                 % declare the paper format.

\usepackage[T1]{fontenc}         % Not always necessary, but recommended.
% End of standard header.  What follows pertains to the problem at hand.

\usepackage{xcolor}
\usepackage{listings}

\lstdefinestyle{Python}{
    language        = Python,
    basicstyle      = \ttfamily,
    keywordstyle    = \color{blue},
    keywordstyle    = [2] \color{teal}, % just to check that it works
    stringstyle     = \color{green},
    commentstyle    = \color{red}\ttfamily
}



\begin{document}

% This must be placed after "\begin{document}":
\lstset{
    frame       = single,
    numbers     = left,
    showspaces  = false,
    showstringspaces    = false,
    captionpos  = t,
    caption     = \lstname
}

Now keywords \emph{are} properly highlighted in the following code snippet:

\begin{lstlisting}[style = Python]
# This is a comment
print("Latex keywordstyles not working?")
if this_is_highlighted:
    print("Yay, this works!")
else:
    print("Why isn't this working?")
\end{lstlisting}

\end{document}

Output:

Output of the code

Related Question