3

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?

0
2

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

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.