[Tex/LaTex] How to paste source code into LaTeX with correct indentation

listingspythonsourcecode

I am trying to use

\begin{lstlisting} 
... 
\end{lstlisting}

to include some Python source code in LaTeX.

When I paste the following code block:

def plot_c(Yhat, Y, X):
    plt.figure()
    plt.plot(X, Y)
    plt.plot(X, Yhat)
    ...

All the indentations are messed up (or removed in this case) like below:

def plot_c(Yhat, Y, X):
plt.figure()
plt.plot(X, Y)
plt.plot(X, Yhat)
...

Is there any way to past source code directly into LaTeX and keep the original format without retyping the source code?

Best Answer

I would recommend the minted package to typeset sourcecode.

Please note section 2 Installation starting at page 4. You need to have python and pygments installed in order to use minted. (Pygments is the name of the package, pygmentize is the name of the program itself.)

Also, (as explained in 3.1 Preliminary on page 6) you must invoke LaTeX with the -shell-escape flag if you want to use minted. For example in TeXstudio open Options > Configure TeXstudio... > Commands and insert pdflatex -shell-escape -synctex=1 -interaction=nonstopmode %.tex for PdfLaTeX.

\documentclass{article}

\usepackage{minted}
\newminted{python}{%
    % options to customize output of pythoncode
    % see section 5.3 Available options starting at page 16
}

\begin{document}
\begin{pythoncode}
def plot_c(Yhat, Y, X):
    plt.figure()
    plt.plot(X, Y)
    plt.plot(X, Yhat)
    ...
\end{pythoncode}
\end{document}

enter image description here