tags:

views:

135

answers:

4

This seems like a trivial question but google has not give me any fast results.

How to do I insert code into a latex document? Is there something like:

\begin{code}
...
\end{code}

Or how should I do this. The only thing that I really need is indentation and a fixed width font. Syntax highlighting could be nice although it is definatly not required.

Thanks, Jake

+9  A: 

Use Listings package.

Simple configuration for LaTeX header (before \begin{document}):

\usepackage{listings}
\usepackage{color}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}

\lstset{frame=tb,
  language=Java,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=none,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{dkgreen},
  stringstyle=\color{mauve},
  breaklines=true,
  breakatwhitespace=true
  tabsize=3
}

You can change default language in the middle of document with \lstset{language=Java}.

Example of usage in the document:

\begin{lstlisting}
// Hello.java
import javax.swing.JApplet;
import java.awt.Graphics;

public class Hello extends JApplet {
    public void paintComponent(Graphics g) {
        g.drawString("Hello, world!", 65, 95);
    }    
}
\end{lstlisting}

Here's the result:

Example Image

Cloudanger
Wow! Awesome exactly what I was looking for.
sixtyfootersdude
I have a follow up question relating to you code. Have a look if you get a chance: http://stackoverflow.com/questions/3408996/insert-code-into-a-latex-doc-without-leading-tabs
sixtyfootersdude
+1  A: 

You could also use the verbatim environment

\begin{verbatim}
your
code
example
\end{verbatim}
midtiby
I tried this but it does not preserve the code indentation.
sixtyfootersdude
There is an issue with using tabs inside the verbatim environment. If tabs are converted to "space" the problem disappears.
midtiby
+2  A: 

Use Pygments !

Tarantula
+4  A: 

Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,

Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.

Philipp