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.
Second, define the language to use, anywhere in the document.
Finally, insert the source code.

  1. write code within your document
    put your code here

  2. import the code from other file

For more information, read

  1. PDF by Carsten Heinz

  2. Listings package on CTAN