[Tex/LaTex] lstinputlistings syntax highlighting

highlightinginputlistingssyntax

I am using package listings to import my Python source code into my LaTeX document. I use the command \lstinputlistings. I have a Python source like

class MyClass(Yourclass):
    def __init__(self, myvar, yours):
        bla bla bla...

What should I write in my \lstset command in order to enlight words MyClass, init etc.? I wouldn't want to write any word I want to be highlighted. I tried using moredelims=[s][\color{teal}]{class}{(} inside lstset but it doesn't work.

And why is morekeywords={...} not working with lstinputlistings. It does with lstlistings environment, but doesn't with input from a source file.

Best Answer

It is always good to post a minimal and compilable example, not just code snippets. This way, the answerers do not have to guess what's happening with your problem.

I guess that you are looking for something like this.

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\lstset{language=Python,
        morekeywords={as,__init__,MyClass},
        keywordstyle=\color{teal}\bfseries,
        }
\begin{document}
\lstinputlisting{guess.py}
\end{document}

where guess.py is your sample code snippet. I just added as on the last line to show that morekeywords works.

class MyClass(Yourclass):
    def __init__(self, myvar, yours):
        bla bla bla... as

Here is the output.

enter image description here

You can also remove __init__ from morekeywords option and use the answers in How to I emphazise all words beginning with ` in an lstlisting and Listings language definition keyword suffixes. So you may put the following code snippet into your preamble.

\lstset{language=Python,
    morekeywords={as,MyClass},
        keywordstyle=\color{teal}\bfseries,
        keywordsprefix=_,
        }

Let me know if this works for you.