How to Format and Highlight Source Code in LaTeX Listings

How to Format and Highlight Source Code in LaTeX Listings

This post may contain affiliate links that allow us to earn a commission at no expense to you. Learn more

LaTeX is popular with professionals because it allows you to insert and format various types of content. If you want to obtain source code highlights for different languages, LaTeX can help you with this. Let’s examine how to use source code in LaTeX listings.

Creating Source Code

Let’s start by looking at a simple example of printing source code in LaTeX

\documentclass[a4paper,12pt]{article}
\usepackage{amssymb} 
\usepackage{amsmath} 
\usepackage[utf8]{inputenc} 
\usepackage[ngerman]{babel} 
 
\usepackage[T1]{fontenc}
\usepackage[margin=2.5cm]{geometry}
\usepackage{listings}
 
\usepackage{hyperref}
 
\begin{document}
    \lstinputlisting[language=Java]{Othello.java}
\end{document}

In the above code, the commands \usepackage{amssymb} and \usepackage{amsmath} are needed for math. The commands \usepackage[utf8]{inputenc} and \usepackage[ngerman]{babel} informs LaTeX to use German amlauts.

The command \usepackage[margin=2.5cm]{geometry} affects the printed source code’s layout. The command \usepackage{listings} informs LaTeX to include the source code in the document. The command \usepackage{hyperref} is needed for adding links in the text.

How to Import Code From a File

Code is generally stored within a source file. It is possible to pull the source code in LaTeX from a file using the command \lstinputlisting[language=LANGUAGENAME]{FILE NAME}. This command also lets you choose which language the code will be in.

If you wish to import only part of the source file, you can mention which lines of code to include. For example, if you wanted to import code lines 3 to 10, the above command would become \lstinputlisting[language=LANGUAGENAME , firstline=3, lastline=10]{FILE NAME}.

Custom Formatting Your Source Code

In some cases, you may wish to format the text in your source in different ways. You can change the font, size, color, and spacing of source code text. We demonstrate how to do this in the following example:

\documentclass[a4paper,12pt]{article}
\usepackage{amssymb} 
\usepackage{amsmath}
\usepackage[utf8]{inputenc}
\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}    
\usepackage[margin=2.5cm]{geometry} 
\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{ %
  language=Java,                
  basicstyle=\footnotesize,     
  numbers=left,               
  numberstyle=\tiny\color{gray},
  stepnumber=1,                                       
  numbersep=5pt,                 
  backgroundcolor=\color{white},  
  showspaces=false,             
  showstringspaces=false,         
  showtabs=false,                 
  frame=single,                   
  rulecolor=\color{black},       
  tabsize=4,                   
  captionpos=b,        
  breaklines=true,             
  breakatwhitespace=false,       
  title=\lstname,                                                  
  keywordstyle=\color{blue},          
  commentstyle=\color{dkgreen},    
  stringstyle=\color{mauve},       
  escapeinside={\%*}{*)},        
  morekeywords={*,...}              
}
 
\usepackage{hyperref}
 
\newcommand{\authorName}{Mark Smith}
\newcommand{\tags}{\authorName, my, tags}
\title{This is the document title}
\author{\Your Author Name}
\date{\today}
 
\hypersetup{
  pdfauthor   = {\Your Author Name},
  pdfkeywords = {\tags},
  pdftitle    = {This is the document title}
}
 
\begin{document}
    \lstinputlisting[language=Java]{Othello.java}
\end{document}

In the above code, the following commands were required for syntax highlighting:

\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}

We then used the command \lstset{…} to create a listing. The codes under this are explained in the following bullet points:

  • language=Java: Sets the code language.
  • basicstyle=\footnotesize: Sets the font size for the fonts used in the code.
  • numbers=left: Indicates where line-numbers are to be placed.
  • numberstyle=\tiny\color{gray}: Sets the style for line-numbers.
  • stepnumber=1: Sets the step number between two line-numbers. Setting this as “1” numbers each line.
  • numbersep=5pt: Sets the distance between line-numbers and the code.
  • backgroundcolor=\color{white}: Sets the background color, but you need to add \usepackage{color} in the preamble.
  • showspaces=false: Informs LaTeX to show spaces for adding underscores.
  • showstringspaces=false: Informs LaTeX to underline the spaces within strings.
  • showtabs=false: Informs LaTeX to show tabs that are within strings while adding underscores.
  • frame=single: Informs LaTeX to add a frame around the printed code.
  • rulecolor=\color{black}: This sets the frame frame-color.

Supported Code Languages

The example above references Java as the source code language. However, LaTeX supports a large number of languages. This includes:

  • ABAP (R/2 4.3, R/2 5.0, R/3 3.1, R/3 4.6C, R/3 6.10)
  • ACSL Ada (83, 95)
  • Algol (60, 68)
  • Ant
  • Assembler (x86masm)
  • Awk (gnu, POSIX), bash, Basic (Visual)
  • C (ANSI, Handel, Objective, Sharp) 
  • C++ (ANSI, GNU, ISO, Visual)
  • Caml (light, Objective)
  • Clean
  • Cobol (1974, 1985, ibm)
  • Comal 80
  • csh
  • Delphi
  • Eiffel
  • Elan
  • erlang
  • Euphoria
  • Fortran (77, 90, 95)
  • GCL
  • Gnuplot
  • Haskell
  • HTML
  • IDL (empty, CORBA)
  • inform
  • Java (empty, AspectJ)
  • JVMIS, ksh
  • Lisp (empty, Auto)
  • Logo
  • make (empty, gnu)
  • Mathematica (1.0, 3.0)
  • Matlab
  • Mercury
  • MetaPost
  • Miranda
  • Mizar
  • ML
  • Modula-2
  • MuPAD
  • NASTRAN
  • Oberon-2
  • OCL (decorative, OMG)
  • Octave, Oz
  • Pascal (Borland6, Standard, XSC)
  • Perl,PHP
  • PL/I,Plasm
  • POV
  • Prolog
  • Promela,Python
  • R
  • Reduce
  • Rexx
  • RSL
  • Ruby 
  • S (empty, PLUS)
  • SAS
  • Scilab
  • Sh
  • SHELXL
  • Simula (67, CII, DEC, IBM)
  • SQL
  • tcl (empty, tk)
  • TeX (AlLaTeX, common, LaTeX, plain, primitive)
  • VBScript
  • Verilog
  • VHDL (empty, AMS)
  • VRML (97)
  • XML
  • XSLT

Final Thoughts

As you can see, LaTeX offers a straightforward route for printing source code. The above guide offers only a basic introduction to the topic. However, the section on customizing source code should prove to be useful for programmers that wish to represent their code in an easy-to-read manner. 

You can learn more about writing source codes in LaTeX from this video.

LaTeX is great at creating professional-looking documents, so any code you print is bound to look fantastic. So try printing source code in your next LaTeX document.

Frequently Asked Questions

Some frequently asked questions related to source code in LaTeX are shown below.

Q1. How to Write Source Code as Text in LaTeX?

You can write source code without the lines being interpreted as code by LaTeX using the commands:
\begin{verbatim}
[YOUR SOURCE CODE]
\end{verbatim}

Q2. How to Insert Code in LaTeX Document With Indentation?

You can add indentation to your code by inserting it using the verbatim environment.
\begin{verbatim}
[YOUR CODE LINE 1]
[YOU CODE LINE 2]
\end{verbatim}


Further Reading

LaTex Tutorial

  1. 27 Pros and Cons of Using LaTex for Scientific Writing
  2. 6 easy steps to create your first Latex document examples
  3. How to add circuit diagrams in Latex
  4. How to change Latex font and font size
  5. How to create a Latex table of contents
  6. How to create footnotes in LaTeX and how to refer to them, using the builtin commands
  7. How to create Glossaries in LaTeX
  8. How to create plots in Latex – codes and examples
  9. How to create symbols in LaTeX – commands for Latex greek alphabet 
  10. How to create tables in LaTeX – rows, columns, pages and landscape tables
  11. How to drawing graphs in Latex – vector graphics with tikz
  12. How to insert an image in LaTeX – Managing Latex figure and picture
  13. How to Itemize and Number List – Adding Latex Bullet Points
  14. How to make hyperlink in latex – Clickable links
  15. How to reference in Latex – 5 steps to bibliography with Bibtex
  16. How to use Latex Packages with examples
  17. How to use LaTeX paragraphs and sections
  18. LaTeX Installation Guide – Easy to follow steps to install LaTex
  19. Learn to typeset and align Latex equations and math

Photo of author
Author
SJ Tsai
Chief Editor. Writer wrangler. Research guru. Three years at scijournal. Hails from a family with five PhDs. When not shaping content, creates art. Peek at the collection on Etsy. For thoughts and updates, hit up Twitter.

Leave a Comment