# How to paste source code into LaTeX with correct indentation

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?

• Use \lstinputlisting{...}. – Andrew Oct 16 '17 at 20:45
• Welcome to TeX.SX! Please note, that this site works best if you (where possible) include a complete compilable minimal working example (MWE) which starts at \documentclass and ends at \end{document}. This way we can help you faster and most likely better! – Skillmon Oct 16 '17 at 20:56
• Where are you copying the code from? This seems to be specific to the editor that you're using, since a copy-and-paste of the code you provided pastes without problem and even includes the proper indentation (in all basic text editors). – Werner Oct 17 '17 at 7:19
• In general, this is the task of the verbatim environment. Various packages provide added functional or syntax improvements to the basic verbatim environment, including listings, minted, verbatimbox, and others. – Steven B. Segletes Oct 17 '17 at 9:37

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}


• thank you for your answer. When source code is already written in some other format, Andrew's comment of using \lstinputlisting{...} did the job without retyping the source code. – Guanghua Shu Oct 22 '17 at 20:07
• The same can be achieved with minted by the \inputminted command (cf. p. 8 of the package's manual) – Stephan Lukasczyk Nov 16 '17 at 9:23
• and there is \newmintedfile to create a shortcut for \inputminted if you want to include several source code files with the same options (see page 30). – jakun Nov 17 '17 at 7:27