LaTeX/Source Code Listings

LaTeX logo.svg


Getting Started
  1. Introduction
  2. Installation
  3. Installing Extra Packages
  4. Basics

Common Elements

  1. Document Structure
  2. Text Formatting
  3. Paragraph Formatting
  4. Colors
  5. Fonts
  6. List Structures
  7. Special Characters
  8. Internationalization
  9. Rotations
  10. Tables
  11. Title creation
  12. Page Layout
  13. Importing Graphics
  14. Floats, Figures and Captions
  15. Footnotes and Margin Notes
  16. Hyperlinks
  17. Labels and Cross-referencing


  1. Errors and Warnings
  2. Lengths
  3. Counters
  4. Boxes
  5. Rules and Struts

Technical Texts

  1. Mathematics
  2. Advanced Mathematics
  3. Theorems
  4. Chemical Graphics
  5. Algorithms
  6. Source Code Listings
  7. Linguistics

Special Pages

  1. Indexing
  2. Glossary
  3. Bibliography Management
  4. More Bibliographies

Special Documents

  1. Letters
  2. Presentations
  3. Teacher's Corner
  4. Curriculum Vitae

Creating Graphics

  1. Introducing Procedural Graphics
  2. MetaPost
  3. Picture
  4. PGF/TikZ
  5. PSTricks
  6. Xy-pic
  7. Creating 3D graphics


  1. Macros
  2. Plain TeX
  3. Creating Packages
  4. Themes


  1. Modular Documents
  2. Collaborative Writing of LaTeX Documents
  3. Export To Other Formats

Help and Recommendations

  1. FAQ
  2. Tips and Tricks


  1. Authors
  2. Links
  3. Package Reference
  4. Sample LaTeX documents
  5. Index
  6. Command Glossary

edit this boxedit the TOC

Using the listings packageEdit

Using the package listings you can add non-formatted text as you would do with \begin{verbatim} but its main aim is to include the source code of any programming language within your document. If you wish to include pseudocode or algorithms, you may find Algorithms and Pseudocode useful also.

To use the package, you need:


The listings package supports highlighting of all the most common languages and it is highly customizable. If you just want to write code within your document the package provides the lstlisting environment:

Put your code here.

Another possibility, that is very useful if you created a program on several files and you are still editing it, is to import the code from the source itself. This way, if you modify the source, you just have to recompile the LaTeX code and your document will be updated. The command is:


in the example there is a Python source, but it doesn't matter: you can include any file but you have to write the full file name. It will be considered plain text and it will be highlighted according to your settings, that means it doesn't recognize the programming language by itself. You can specify the language while including the file with the following command:


You can also specify a scope for the file.

\lstinputlisting[language=Python, firstline=37, lastline=45]{}

This comes in handy if you are sure that the file will not change (at least before the specified lines). You may also omit the firstline or lastline parameter: it means everything up to or starting from this point.

This is a basic example for some Pascal code:

}             % Include the listings-package
}          % Set your language (you can change the language for each code-block optionally)

\begin{lstlisting}[frame=single]  % Start your code-block
for i:=maxint to 0 do
{ do nothing }
Write(’Case insensitive ’);
Write(’Pascal keywords.’);


Latex Pascal Listing.png

Supported languagesEdit

It supports the following programming languages:

ACSL inform Plasm
Ada4 Java4 POV
Algol4 JVMIS Prolog
Ant ksh Promela
Assembler2,4 Lisp4 Python
Awk4 Logo R
bash make4 Reduce
Basic2,4 Mathematica1,4 Rexx
C4 Matlab RSL
C++4 Mercury Ruby
Caml4 MetaPost S4
Clean Miranda SAS
Cobol4 Mizar Scilab
Comal ML sh
csh Modelica3 SHELXL
Delphi Modula-2 Simula4
Eiffel MuPAD SQL
Elan NASTRAN tcl4
erlang Oberon-2 TeX4
Euphoria OCL4 VBScript
Fortran4 Octave Verilog
Gnuplot Pascal4 VRML4
Haskell Perl XML

For some of them, several dialects are supported. For more information, refer to the documentation that comes with the package, it should be within your distribution under the name listings-*.dvi.

  1. It supports Mathematica code only if you are typing in plain text format. You can't include *.NB files \lstinputlisting{...} as you could with any other programming language, but Mathematica can export in a pretty-formatted LaTeX source.
  2. Specification of the dialect is mandatory for these languages (e.g. language={[x86masm]Assembler}).
  3. Modelica is supported via the dtsyntax package available here.
  4. For these languages, multiple dialects are supported. C, for example, has ANSI, Handel, Objective and Sharp. See p. 12 of the listings manual for an overview.

  1. include<iostream>
  2. include<fstream>
  3. include<cstring>

using namespace std;

void reverse (char*s) //we need the void function to display something, moreover it returns nothing { int len = strlen(s); //we declared string length and assigned it to strlen(s) the length of the string in C format char temp; for(int i=0; i<len/2; i++) {

       temp = * (s+i); //we save the particular character's  value in temp 

*(s+i) = * (s+ len -i -1);//we change the values symetrically from the beginning and from the end of particular symetrycal characters

       * (s+ len -i -1)  =temp; //we save the last particular characters in temp

} }

int main() { ifstream inputFile; //declaration of input file

   ofstream outputFile ("output.txt");// we create the file output.txt where we input the datas
       //we can also input datas in the next way inputFile>><datas>
   char line[500];"input.txt");
                        cerr<<"error in opening the file"<<endl;
    for(int j=0; j<10; j++)
   for(int i = 0; i < strlen(line); i++){
           cout << line[i];
   cout << "             ";
   for(int i = 0; i < strlen(line); i++){//in case we wrote i<500, we would have had something abnormal!!!!!!!
           cout << line[i];
          outputFile << line[i];

cout << endl; }

   cout << endl;
    inputFile.close();//we close the file, to allocate the memory :))


return 0; }

Automating file inclusionEdit

If you have a bunch of source files you want to include, you may find yourself doing the same thing over and over again. This is where macros show their real power.

\newcommand{\includecode}[2][c]{\lstinputlisting[caption=#2, escapechar=, style=custom#1]{#2}}
% ...

% ...


In this example, we create one command to ease source code inclusion. We set the default style to be customc. All listings will have their name as caption: we do not have to write the file name twice thanks to the macro. Finally we list all listings with this command from the listings package.

See Macros for more details.

Encoding issueEdit

By default, listings does not support multi-byte encoding for source code. The extendedchar option only works for 8-bits encodings such as latin1.

To handle UTF-8, you should tell listings how to interpret the special characters by defining them like so

  {á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1 {ó}{{\'o}}1 {ú}{{\'u}}1
  {Á}{{\'A}}1 {É}{{\'E}}1 {Í}{{\'I}}1 {Ó}{{\'O}}1 {Ú}{{\'U}}1
  {à}{{\`a}}1 {è}{{\'e}}1 {ì}{{\`i}}1 {ò}{{\`o}}1 {ù}{{\`u}}1
  {À}{{\`A}}1 {È}{{\'E}}1 {Ì}{{\`I}}1 {Ò}{{\`O}}1 {Ù}{{\`U}}1
  {ä}{{\"a}}1 {ë}{{\"e}}1 {ï}{{\"i}}1 {ö}{{\"o}}1 {ü}{{\"u}}1
  {Ä}{{\"A}}1 {Ë}{{\"E}}1 {Ï}{{\"I}}1 {Ö}{{\"O}}1 {Ü}{{\"U}}1
  {â}{{\^a}}1 {ê}{{\^e}}1 {î}{{\^i}}1 {ô}{{\^o}}1 {û}{{\^u}}1
  {Â}{{\^A}}1 {Ê}{{\^E}}1 {Î}{{\^I}}1 {Ô}{{\^O}}1 {Û}{{\^U}}1
  {œ}{{\oe}}1 {Œ}{{\OE}}1 {æ}{{\ae}}1 {Æ}{{\AE}}1 {ß}{{\ss}}1
  {ç}{{\c c}}1 {Ç}{{\c C}}1 {ø}{{\o}}1 {å}{{\r a}}1 {Å}{{\r A}}1
  {}{{\EUR}}1 {£}{{\pounds}}1

The above table will cover most characters in latin languages. For a more detailed explanation of the usage of the literate option check section 5.4 in the Listings Documentation.

Nonetheless, commenting source code in a language other than English is often considered bad practice. English normally allows your source code to be widely understood and maintained.

Customizing captionsEdit

You can have fancy captions (or titles) for your listings using the caption package. Here is an example for listings.


\DeclareCaptionFont{white}{ \color{white} }
  \colorbox[cmyk]{0.43, 0.35, 0.35,0.01 }{
\captionsetup[lstlisting]{ format=listing, labelfont=white, textfont=white, singlelinecheck=false, margin=0pt, font={bf,footnotesize}

% ...

\lstinputlisting[caption=My caption]{sourcefile.lang}


A lot more detailed information can be found in a PDF by Carsten Heinz and Brooks Moses.

Details and documentation about the Listings package can be found at its CTAN website.

Previous: Algorithms Index Next: Linguistics
Last modified on 22 April 2014, at 16:37