114

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 Child(Parent):
    def __init__(self, *args, **kwargs):
        bla bla bla...

What should I write in my \lstset command in order to highlight 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.

fmonegaglia
  • 1,754
  • 1
    And why is morekeywords={...} not working with lstinputlistings. It does with lstlistings environment, but doesn't with input from a source file. – fmonegaglia Nov 21 '12 at 16:13
  • 6
    I'd recommend using minted instead or pythontex. They produce much better results and also the default highlighting is already coloured (and the colours are nice). Anyway this should really be posted in TeX Exchange as unutbu said. (On a side note: don't add information as comment, edit your question). – Bakuriu Nov 21 '12 at 16:22

4 Answers4

146

Good approach is defining new environments for programming language. Minimal setup can be around this:

\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}

% Default fixed font does not support bold face \DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{12} % for bold \DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{12} % for normal

% Custom colors \usepackage{color} \definecolor{deepblue}{rgb}{0,0,0.5} \definecolor{deepred}{rgb}{0.6,0,0} \definecolor{deepgreen}{rgb}{0,0.5,0}

\usepackage{listings}

% Python style for highlighting \newcommand\pythonstyle{\lstset{ language=Python, basicstyle=\ttm, morekeywords={self}, % Add keywords here keywordstyle=\ttb\color{deepblue}, emph={MyClass,init}, % Custom highlighting emphstyle=\ttb\color{deepred}, % Custom highlighting style stringstyle=\color{deepgreen}, frame=tb, % Any extra options here showstringspaces=false }}

% Python environment \lstnewenvironment{python}[1][] { \pythonstyle \lstset{#1} } {}

% Python for external files \newcommand\pythonexternal[2][]{{ \pythonstyle \lstinputlisting[#1]{#2}}}

% Python for inline \newcommand\pythoninline[1]{{\pythonstyle\lstinline!#1!}}

\begin{document}

\section{``In-text'' listing highlighting}

\begin{python} class MyClass(Yourclass): def init(self, my, yours): bla = '5 1 2 3 4' print bla \end{python}

\section{External listing highlighting}

\pythonexternal{demo.py}

\section{Inline highlighting}

Definition \pythoninline{class MyClass} means \dots

\end{document}

Output:

enter image description here

inavda
  • 136
  • 1
  • 7
redmode
  • 1,769
  • 2
    very nice, helped me a lot. My suggestion is to add \small to all styles, to make it smaller. Right now the code looks clumsy and big to me – kadir May 11 '14 at 22:39
  • 2
    Have to look at this more later, I implemented this but then I had lines with answers to question c) where I was putting that in Math Mode: $c)$ and this was tripping up the utf-8 encoding and some other errors, but otherwise this is awesome!! +1 – JimLohse Oct 10 '16 at 03:24
  • 1
    This seems to not understand """triple quoted strings""". Any chance there is some wizardry to make this happen? I've been looking for things that can be passed to \lstset, but so far I've come up with nothing useful (only ways to change the color of strings). – Bailey Parker Mar 09 '18 at 05:20
  • 2
    Nevermind, found the incantation. It's morestring=[s]{"""}{"""}. Found it here: https://tex.stackexchange.com/a/235742/156739 – Bailey Parker Mar 09 '18 at 05:31
  • 2
    Any chance of getting a listing number and caption with this method? – Luís de Sousa Jun 05 '19 at 13:58
  • 1
    @redmode: great answer, thx so much! ... is there a way to add a subcaption to the code? Such as: Listing 1: "my caption". ? – Luk Jun 19 '20 at 08:56
  • I asked a question about how to caption it? https://tex.stackexchange.com/q/590342/143861 – minseong Mar 28 '21 at 10:20
74

I found this python package pythonhighlight on Github

Define it like this \usepackage{pythonhighlight} and use it like this:

\begin{python}
def f(x):
    return x
\end{python}
CodingYourLife
  • 961
  • 8
  • 5
  • 6
    Nice. The support for inline code using \pyth{print("Hello World!")} was really helpful! – Giacomo Pigani Feb 07 '19 at 20:47
  • 4
    Grand - and it is even available in Ubuntu's standard packages (apt show texlive-science | grep python). – Gerald Senarclens de Grancy Jun 23 '19 at 13:26
  • 1
    very nice package ! love it ! – firdaus Dec 19 '19 at 16:29
  • 4
    This answers to the point. This should have been the accepted answer. – Prasad Raghavendra Mar 31 '20 at 00:04
  • How is this not the accepted answer? Wonderful, single line change. The right level of abstraction for the problem. (Also, incidentally, this method produced color successfully on my end, whereas the accepted answer did not.) – ashman Jan 24 '21 at 19:27
  • 4
    Note that it is based on listings, and internally creates a style named mypython, so you can create derived styles directly (even if it's not documented, I just hope they wont later change the name of the environment). Practical if you want to add line numbering for instance using \lstnewenvironment{pythonLines}[1][]{\lstset{style=mypython,numbers=left}}{}, and then in your document \begin{pythonLines}your python code\end{pythonLines} – tobiasBora May 13 '21 at 06:24
  • Any way to include mathematical symbols in this? – user2757771 Apr 19 '22 at 18:04
21

I'd consider running your code through pygments to generate the latex, probably using the minted package. You can get some details here https://stackoverflow.com/questions/1966425/source-code-highlighting-in-latex#1985330 .

6

Some while ago I have modified the existing python language-definition from the listings-package:

Listings: syntax for literate

You might find something useful. If I remember correctly, one can put all this in an external *.sty-file. Also see the follow-up question.

another problem

BadAtLaTeX
  • 1,139
  • How do you I remove the first quotation marks? Even though my code doesn't have the quotation marks. In the output PDF the quotation marks appear. I couldn't figure out what creates those quotation marks? – nxkryptor Jan 04 '18 at 06:51
  • @nxkryptor: that was a bug that appeared, because I forgot the comma after some command. See the linked follow up; its code should have that fixed. It was mentioned in the answer of the first question though. – BadAtLaTeX Jan 04 '18 at 09:50