Inserting code snippets

Here is some syntax you can use to insert code snippets and code highlighting in a text flow.

You can use the listings, boxhandler and verbatimbox packages for source code.

1
2
3
    \usepackage{listings}
    \usepackage{boxhandler}
    \usepackage{verbatimbox}

However, I found the Listing packagelstset best suited my needs for technical documentation. from the Listing package documentation:

The listings package is a source code printer for LATEX. You can typeset stand alone files as well as listings with an environment similar to verbatim as well as you can print code snippets using a command similar to \verb. Many parameters control the output and if your preferred programming language isn’t already supported, you can make your own definition.

Code highlighting

You can put code inside a corresponding environment.

For example, for SQL commands, you could use the following.

1
2
3
\begin(codesql)
SQL Command syntax, etc.
\end(codesql)

Other examples are:

verbatim

LaTeX provides a default command verbatim for inserting code. It ignores all text and commands within the environment and outputs the text in monospaced font.

1
2
3
4
5
6
7
8
9
10
11
\begin{verbatim}
    /* HelloWorld.java
    */

    public class HelloWorld
    {
        public static void main(String[] args) {
	        System.out.println("Hello World!");
        }
    }
\end{verbatim}

listings package

The listings package supports most common languages. To include this package, add the following line to the stylesheet.

1
\usepackage{listings}

First, I defined the colours for the source code as follows:

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\definecolor{lightgrey}{RGB}{211,211,211}

Then I configured \lstset as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
\lstset{
  frame=tlrb,
  frameround=tttt,
  framerule=0.2pt,
  rulecolor=\color{lightgrey},
  language=SQL,
  aboveskip=3mm,
  belowskip=3mm,
  showstringspaces=false,
  columns=flexible,
  basicstyle={\small\ttfamily},
  numbers=none,
  numberstyle=\tiny\color{gray},
  keywordstyle=\color{blue},
  commentstyle=\color{dkgreen},
  stringstyle=\color{mauve},
  breaklines=true,
  breakatwhitespace=true tabsize=3
}

\lstset{language=SQL}

\newcommand{\inlineCode}{\lstinline[basicstyle=\normalsize\ttfamily]}

Then when I want to insert some code, I use this macro as follows:

1
2
3
4
5
\begin{lstlisting}

  INSERT CODE HERE

\end{lstlisting}

You add your code sample using the following syntax, changing the language setting accordingly.

1
2
3
4
5
6
7
8
9
10
11
\begin{lstlisting}[language=java]
    /* HelloWorld.java
    */

    public class HelloWorld
    {
        public static void main(String[] args) {
        System.out.println("Hello World!");
       }
    }
\end{lstlisting}