LaTeX Code Listings

Overview

The lstinputlisting command can be used to generated style code listings directly within the document. This feature is great for documenting code or adding it into a document for reference purposes. Useful links: Overleaf and Wiki.

By default lstinputlisting only supports certain languages for syntax highlighting. Matlab is not a supported langauge for syntax highlighting, but nasa-latex-docs has extended functionality to also support Matlab syntax highlighting! Another free benefit of using nasa-latex-docs. See examples below.

Simple Code Listings

\lstinputlisting[caption=Example C++, label={lst:listing-cpp}, language=C++]{code_sample.cpp}
../_images/listing_cpp.png

Customization Options

Code listings can be customized in a variety of ways. The following is a summary of the various options. More details on each can be researched by the end user - this simply serves as a cursory reference.

backgroundcolor=\color{white},   % choose the background color
basicstyle=\footnotesize,        % the size of the fonts that are used for the code
breakatwhitespace=false,         % sets if automatic breaks should only happen at whitespace
breaklines=true,                 % sets automatic line breaking
captionpos=b,                    % sets the caption-position to bottom
commentstyle=\color{mygreen},    % comment style
deletekeywords={...},            % if you want to delete keywords from the given language
escapeinside={\%*}{*)},          % if you want to add LaTeX within your code
extendedchars=true,              % lets you use non-ASCII characters; for 8-bits encodings only, does not work with UTF-8
firstnumber=1000,                % start line enumeration with line 1000
frame=single,                    % adds a frame around the code
keepspaces=true,                 % keeps spaces in text, useful for keeping indentation of code (possibly needs columns=flexible)
keywordstyle=\color{blue},       % keyword style
language=Octave,                 % the language of the code
morekeywords={*,...},            % if you want to add more keywords to the set
numbers=left,                    % where to put the line-numbers; possible values are (none, left, right)
numbersep=5pt,                   % how far the line-numbers are from the code
numberstyle=\tiny\color{mygray}, % the style that is used for the line-numbers
rulecolor=\color{black},         % if not set, the frame-color may be changed on line-breaks within not-black text (e.g. comments (green here))
showspaces=false,                % show spaces everywhere adding particular underscores; it overrides 'showstringspaces'
showstringspaces=false,          % underline spaces within strings only
showtabs=false,                  % show tabs within strings adding particular underscores
stepnumber=2,                    % the step between two line-numbers. If it's 1, each line will be numbered
stringstyle=\color{mymauve},     % string literal style
tabsize=2,                       % sets default tabsize to 2 spaces

Creating a Predefined Style

In order to reuse styles, the \lstdefinestyle command can be used to define a custom style configuration using the options defined in the previous section.

\lstdefinestyle{myStyle}{
    belowcaptionskip=1\baselineskip,
    breaklines=true,
    frame=none,
    numbers=none,
    basicstyle=\footnotesize\ttfamily,
    keywordstyle=\bfseries\color{green!40!black},
    commentstyle=\itshape\color{purple!40!black},
    identifierstyle=\color{blue},
    backgroundcolor=\color{gray!10!white},
}

Setting a Local Style

User can define a style configuration to be used for a specific code listing using the style keyword:

\lstinputlisting[caption=Example C++, label={lst:listing-cpp}, language=C++, style=myStyle]{code_sample.cpp}

Setting a Global Style

User can define a style configuration to be used as the default for all code listings using the lstset command:

\lstset{style=myStyle}

Customization of Code Listings - Style

The following is an example of using an existing pre-defined style to customize a code listing.

\lstdefinestyle{myStyle}{
    belowcaptionskip=1\baselineskip,
    breaklines=true,
    frame=none,
    numbers=none, 
    basicstyle=\footnotesize\ttfamily,
    keywordstyle=\bfseries\color{green!40!black},
    commentstyle=\itshape\color{purple!40!black},
    identifierstyle=\color{blue},
    backgroundcolor=\color{gray!10!white},
}

\lstinputlisting[
    caption=Example C++,
    label={lst:listing-cpp},
    language=C++,
    style=myStyle,
    ]{code_sample.cpp}
../_images/listing_customize_style.png

Customization of Code Listings - Manual

If a style is not define, users can manually apply certain styles. This method can also be used to override default styles.

\definecolor{codegreen}{rgb}{0,0.6,0}
\definecolor{codegray}{rgb}{0.5,0.5,0.5}
\definecolor{codepurple}{rgb}{0.58,0,0.82}
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}

\lstinputlisting[
    caption=Example C++,
    label={lst:listing-cpp},
    language=C++,
    backgroundcolor=\color{backcolour},   
    commentstyle=\color{codegreen},
    keywordstyle=\color{magenta},
    numberstyle=\tiny\color{codegray},
    stringstyle=\color{codepurple},
    basicstyle=\ttfamily\footnotesize,
    breakatwhitespace=false,         
    breaklines=true,                 
    keepspaces=true,                 
    numbers=left,       
    numbersep=5pt,                  
    showspaces=false,                
    showstringspaces=false,
    showtabs=false,                  
    tabsize=2,
    ]{code_sample.cpp}
../_images/listing_customize.png

Referencing Code Listings

The example below highlights how the \label command is used to define a unique label to this specific code listing and how it can be referenced within the text of the document using the \ref command.

\lstinputlisting[caption=Example C++, label={lst:listing-cpp}, language=C++]{code_sample.cpp}

An example table can be seen in \ref{lst:listing-cpp}.
Also note how the "Listing" prefix is automatically added within the document text whenever the reference is called.
../_images/listing_reference.png

Referencing Range of Code Listings

The example below highlights how the \refrange command can be used to reference a range of code listings.

% Define a custom color
\definecolor{backcolour}{rgb}{0.95,0.95,0.92}
\definecolor{codegreen}{rgb}{0,0.6,0}

% Define a custom style
\lstdefinestyle{myStyle}{
    backgroundcolor=\color{backcolour},   
    commentstyle=\color{codegreen},
    basicstyle=\ttfamily\footnotesize,
    breakatwhitespace=false,         
    breaklines=true,                 
    keepspaces=true,                 
    numbers=left,       
    numbersep=5pt,                  
    showspaces=false,                
    showstringspaces=false,
    showtabs=false,                  
    tabsize=2,
}

% Use \lstset to make myStyle the global default
\lstset{style=myStyle}

\lstinputlisting[caption=Sample Code Listing C++, label={lst:listing-cpp}, language=C++]{code_sample.cpp}

\lstinputlisting[caption=Sample Code Listing Python, label={lst:listing-python}, language=Python]{code_sample.py}

\lstinputlisting[caption=Sample Code Listing Matlab, label={lst:listing-matlab}, language=Matlab]{code_sample.m}

We can reference a range of tables as seen here: \refrange{lst:listing-cpp}{lst:listing-matlab}.
Also note how the "Listings" prefix is automatically added within the document text whenever the range reference is called.
../_images/listing_reference_range.png