Adding programming code into LaTex / LyX

My favorite environment for this minted. I use it to input entire source files such as:

\inputminted[linenos,fontsize=\scriptsize]{python}{script.py}

You can also use it without inputing a file, and more importantly, define how much indent it gobbles once pasted:

\newminted{python}{gobble=4,linenos,fontsize=\scriptsize}
\begin{pythoncode}
    print('I am a Python script')
\end{pythoncode}

That way your LaTeX is still nicely indented, but your verbatim code is not. This also provides syntax-highlighting, which I know you mentioned you weren't interested in. Just don't define the language.


You'll want to use the verbatim environment: http://web.mit.edu/vogt/www/latex/ltx-79.html

If the problem is immediately when you paste it in... are you using an IDE to make the document? Try just opening the file in a plain text editor like gedit or notepad.


I'd go with minted, as fideli suggested, but it's good to be aware of the listings package, which is a pure Latex solution ot the problem.

minted is derived from Pygments, a source highlighter written in Python. minted coimes with a Latex bridge, based on \write18, and the texments package provides one for Pygments. There's no downside to minted compared to Pygments that I know of: maybe the two will be merged at some point.


To use the listings package, you'll have to include the package and load necessary languages in the preamble:

\usepackage{listings}
\lstloadlanguages{Python}

Set some options inside the document:

\lstset{language=Python,tabsize=2}

... and then you can either give snippets inline:

\begin{lstlisting}
  print ("Hello, World!")
\end{lstlisting}

... or read them from a file:

\lstinputlisting[firstline=10,lastline=20]{Hello.py}

... or write the code inline: \lstinline!print ("Hello, World!")!


For LyX, see this (imports a child document using the "listing" format).