Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Maybe I'm just being thick, but I can't find any sensible way to simply paste in my (python) code into latex without losing all the indent information (kinda important for python).

Anyone got any bright ideas? I'm not worried about syntax highlighting; all I want is my tab key back!

share|improve this question

5 Answers 5

up vote 9 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

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.

share|improve this answer

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!")!

share|improve this answer

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.