Tag Archives: code

LaTeX syntax highlighting examples

Syntax highlighting in LaTeX using the listings package is very powerful. Below, I will provide a few examples for your convenience.

First, let me briefly summarize the usage of the listings package.

\usepackage{listings}
\usepackage{color}
\definecolor{name}{rgb}{0.5,0.5,0.5}
...
\lstset{key1=value1,
key2=value2}
...
\begin{lstlisting}
Code
\end{lstlisting}
...
\lstinputlisting{filename.java}

So below you’ll find a few complete code examples to reuse and modify for your purposes:

“The Pseudo Code Box”

\definecolor{lightpurple}{rgb}{0.8,0.8,1}

\lstset{
numbers=left,
stepnumber=1,
numbersep=5pt,
numberstyle=\small\color{black},
basicstyle=\ttfamily,
keywordstyle=\color{black},
commentstyle=\color{black},
stringstyle=\color{black},
frame=single,
tabsize=2,
backgroundcolor=\color{lightpurple},
caption=Fibonacci numbers pseudo code}

I copied the code from here

“OOP: Java”

\definecolor{javared}{rgb}{0.6,0,0} % for strings
\definecolor{javagreen}{rgb}{0.25,0.5,0.35} % comments
\definecolor{javapurple}{rgb}{0.5,0,0.35} % keywords
\definecolor{javadocblue}{rgb}{0.25,0.35,0.75} % javadoc

\lstset{language=Java,
basicstyle=\ttfamily,
keywordstyle=\color{javapurple}\bfseries,
stringstyle=\color{javared},
commentstyle=\color{javagreen},
morecomment=[s][\color{javadocblue}]{/**}{*/},
numbers=left,
numberstyle=\tiny\color{black},
stepnumber=2,
numbersep=10pt,
tabsize=4,
showspaces=false,
showstringspaces=false}

Java output example

“The Trickiest: LaTeX”

\definecolor{lightgrey}{rgb}{0.9,0.9,0.9}
\definecolor{darkgreen}{rgb}{0,0.6,0}

\lstset{language=[LaTeX]TeX,
texcsstyle=*\bf\color{blue},
numbers=none,
breaklines=true,
keywordstyle=\color{darkgreen},
commentstyle=\color{red},
otherkeywords={$, \{, \}, \[, \]},
frame=none,
tabsize=2,
backgroundcolor=\color{lightgrey},
caption=LaTeX example}

The LaTeX code was copied from here.


Generating dummy text/blindtext with Latex for testing

I was often using any of the available “lorem ipsum” generators on the web while testing different things in Latex until I discovered that the Latex distribution provides packages generating blind text, which is definitely more convenient. With just a few lines of code, these packages will generate paragraphes, even whole documents with sections, paragraphs of text, lists, etc.

The first package that I will introduce is the “blindtext” package. First the language option as well as the package have to be loaded. Make sure you get the order right, otherwise your text might appear in latin by default.

\usepackage[english]{babel}
\usepackage{blindtext}

The language options english, (n)german and latin are available. French is also available, but in a preliminary version. Try it out yourself :-) .

Now you are ready to create a paragraph or even a whole document with just one line of code.

For few/more paragraphs of normal text:

\blindtext
\Blindtext

For a small/large document:

\blinddocument
\Blinddocument

In an arbitrary number of repetitions, e.g.

\blindtext[5]

Furthermore,

\blindlist{env}[x]

creates a list with “x” being the number of items generated. The environment can be set to itemize, enumerate or description.

A more direct way to generate lists is by using the commands:

\blinditemize
\blindenumerate
\blinddescription

and their extended versions with capital letters are available. Similarly, the number of items is defined through the optional argument, e.g.

\blindenumerate[10]

If you want math within the text, use

\blindmathtrue
\blindmathfalse

respectively.

It is also possible to generate text with math including formulas, using

\blindmathpaper

The “lipsum” package is a more basic package. It generates a certain number of the standard “lorem ipsum” text:

\usepackage{lipsum}
...
\lipsum
\lipsum[3-56]

By default, the package will either generate slightly more than a single page (fist line). Alternatively, it generates an arbitrary number of paragraphs (second line).

For more information, please refer to the package information of the blindtext as well as the lipsum packages.


Check syntax only, save time typesetting!

Working on a large document? Producing output can take quite some time, but with the following tricks you can save some of it…

Add the following two lines to your preamble and Latex will not produce any output pages, while still checking that your syntax is correct and working.

\usepackage{syntonly}
\syntaxonly

Just comment out the second line if you want to see the output file:

\usepackage{syntonly}
% \syntaxonly


Include source code in Latex with “Listings”

 First include the “listings”-package into your document:

\usepackage{listings}

Basics

Now you have basically two possibilities. Either you type/copy your source code directly into the Latex document:

\begin{lstlisting}
place your source code here
\end{lstlisting}

The other possibility is to directly include the source file:

\lstinputlisting{filename.java}

This is particularly useful if you are still editing your source code. Obviously, Latex will always include the latest version of the source while generating the PDF-file.

Supported languages

The listings package does not only support java source code, but there is an exhaustive list of languages which are known to the package:
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.

Custom code formatting

You can customise the way how your code is displayed by using:

\lstset{...}

The following is a list of parameters, which can be used inside the previous command

language=Octave -> choose the language of the code
basicstyle=\footnotesize -> the size of the fonts used for the code
numbers=left -> where to put the line-numbers
numberstyle=\footnotesize -> size of the fonts used for the line-numbers
stepnumber=2 -> the step between two line-numbers.
numbersep=5pt -> how far the line-numbers are from the code
backgroundcolor=\color{white} -> sets background color (needs package)
showspaces=false -> show spaces adding particular underscores
showstringspaces=false -> underline spaces within strings
showtabs=false -> show tabs within strings through particular underscores
frame=single -> adds a frame around the code
tabsize=2 -> sets default tab-size to 2 spaces
captionpos=b -> sets the caption-position to bottom
breaklines=true -> sets automatic line breaking
breakatwhitespace=false -> automatic breaks happen at whitespace
morecomment=[l]{//} -> displays comments in italics (language dependent)

If you are using several parameters, they have to be separated by commas.
Example:

\lstset{numbers=left, stepnumber=2, frame=single,}

You might want to have a caption as well as reference the listing later:

\lstset{language=Java, caption=Descriptive Caption Text, label=DescriptiveLabel}

For an exhaustive list of available options to customize your included source code, refer to the documentation on CTAN.

Tricks

The following will draw a frame around your source code with a blue shadow (you will need the color-package).

\lstset{frame=shadowbox, rulesepcolor=\color{blue}}

If you want closed frames on each page, use the following command sequence:

\begin{framed}
\begin{lstlisting}...\end{lstlisting}
or \lstinputlisting{...}
\end{framed}


Placing figures/tables side-by-side (\minipage)

Including images in a report is very common in Latex. Structuring your work nicely is probably the most obvious reason why you want to put two figures/tables side-by-side. Another reason might be to save space, wherever a smaller size of an image is sufficient. The following code can be used to place two figures side-by-side by creating a minipage…

\begin{figure}[ht]
\begin{minipage}[b]{0.5\linewidth}
\centering
\includegraphics[width=\textwidth]{filename1}
\caption{default}
\label{fig:figure1}
\end{minipage}
\hspace{0.5cm}
\begin{minipage}[b]{0.5\linewidth}
\centering
\includegraphics[width=\textwidth]{filename2}
\caption{default}
\label{fig:figure2}
\end{minipage}
\end{figure}

Note, for certain figure manipulations such as width, loading the graphicx package is required:

\usepackage{graphicx}

The same “local column” – effect can be achieved for tables. The following code shows you how:

\begin{table}[ht]
\begin{minipage}[b]{0.5\linewidth}\centering
\begin{tabular}{|c|c|c|}
\hline
1&1&1\\
\hline
2&2&2\\
\hline
\end{tabular}
\end{minipage}
\hspace{0.5cm}
\begin{minipage}[b]{0.5\linewidth}
\centering
\begin{tabular}{|c|c|c|}
\hline
1&1&1\\
\hline
2&2&2\\
\hline
\end{tabular}
\end{minipage}
\end{table}

You can also have more than two column simply by adding another \minipage in between the table-command and reduce the width of each \minipage (0.33\linewidth in addition to the \hspace). LaTex will automaticaly place objects onto the next line, if space is not sufficient.

Remark: Using the subfigure-package is another way to place figures or tables side-by-side. You might want to have a look at this post on subfigures.


Formatting code in LaTex (tabbing, verbatim)

Formatting code in LaTex is as astonishingly easy, once one knows how to do it.

There is a command “tabbing”, which is used in the same way as for example “centering”, except that one has to tell the computer where to set a tab.

\begin{tabbing}
if \= (condition) \{ \\ % inserts a tab just after the "if"-command.
\> then statement \=\\ % go to the defined tab and set a new one
\}\\
else \{ \\
\> else statement     \> next tab is here\\
\}\\
\end{tabbing}

Copy-paste the code into your LaTex-file and see yourself.

One can use as many \> in a sequence as needed, as long as enough tabs have been defined before.

E.g.

\begin{tabbing}
o \= o \= o\\
o \> \> o\\
o \> o \> o\\
\end{tabbing}

Another way to just format your code if you already have it in a “tabbed” version is to use “verbatim”.

\begin{verbatim}
Your code goes here.
\end{verbatim}


Follow

Get every new post delivered to your Inbox.

Join 316 other followers