Wednesday, May 27, 2009

Insert source code with syntax highlighting in LaTeX

To insert source code with syntax highlighting, one possibility is to use the Listings package.

The Listings package supports a huge number of languages: ABAP, IDL, Plasm, ACSL, inform, POV, Ada, Java, Prolog, Algol, JVMIS, Promela, Ant, ksh, Python, Assembler, Lisp, R, Awk, Logo, Reduce, bash, make, Rexx, Basic, Mathematica1, RSL, C, Matlab, Ruby, C++, Mercury, S, Caml, MetaPost, SAS, Clean, Miranda, Scilab, Cobol, Mizar, sh, Comal, ML, SHELXL, csh, Modula-2, Simula, Delphi, MuPAD, SQL, Eiffel, NASTRAN, tcl, Elan, Oberon-2, TeX, erlang, OCL, VBScript, Euphoria, Octave, Verilog, Fortran, Oz, VHDL, GCL, Pascal, VRML, Gnuplot, Perl, XML, Haskell, PHP, XSLT, HTML, and PL/I.



To use the Listings package, first define the package in the preamble.
\usepackage{listings}
Second, define the language to use, anywhere in the document.
\lstset{language=Python}
Finally, insert the source code.

  1. write code within your document
    \begin{lstlisting}
    put your code here
    \end{lstlisting}

  2. import the code from other file
    \lstinputlisting{source_filename.py}

For more information, read

  1. PDF by Carsten Heinz

  2. Listings package on CTAN