Decorating text in LaTeX

| Comments (0) | Software
One problem I ran into lately was how to decorate LaTeX text. In particular, I had some source code and wanted to draw arrows between elements. This isn't something that LaTeX supports out of the box, but once again comp.text.tex to the rescue. The two major solutions appear to be:
  • pstricks (only works if you're generating PostScript)
  • tikz/pgf

Because I generate PDF directly with pdflatex, pstricks was out. Luckily, tikz + PGF works handily. The relevant code looks something like this.

\documentclass[letterpaper]{article}

\usepackage{listings}
\usepackage{tikz}

\lstset{escapechar=\%}

\tikzstyle{every picture}+=[remember picture]
\tikzstyle{na} = [baseline=-.5ex]

\begin{document}
\begin{lstlisting}
void example(FILE *fp)
{
  int c;

  while((c=fgetc(fp)!=EOF)){
    if(c=='X')
      %\tikz[na] \coordinate(source);%goto done;
    fputc(c,stdout);
  }

%\tikz[na] \coordinate(target);%done:
  exit(0);
}
\end{lstlisting}

\begin{tikzpicture}[overlay]
\path[->, red, thick] (source) edge [bend right] (target);
\end{tikzpicture}
\end{document}

The output looks like this.. In order to make tikz work you need to:

  • Set tikz coordinates at source and destination
  • Create a tikz picture that draws an arrow between the coordinates. This must be set as an overlay.
  • Run pdflatex twice. This is necessary because the document needs to be built in order to generate the coordinates that tikz will then want to draw on.
I've also demonstrated this using the listings package, which ignores any LaTeX commands in the source it's formatting. In order to bypass this you need to set up an escape character (see the lstset directive), which lets you escape into LaTeX from listings. Hence the bracketing of the tikz commands with %.

Leave a comment