% !TEX TS-program = knitr
% \VignetteIndexEntry{The tikzDevice Package}
% \VignetteDepends{tikzDevice}
% \VignetteEngine{knitr::knitr}

\documentclass[10pt,oneside,letterpaper,article]{memoir}
\usepackage[utf8]{inputenc}
\usepackage{tikzDeviceVignette}


<<setup,echo=FALSE,results='hide'>>=
  library(tikzDevice)
  if( !file.exists('figs') ){dir.create( 'figs' )}

  options(tikzMetricsDictionary='.tikzMetrics')

  knitr::opts_chunk$set(
    echo=FALSE,
    fig.path='figs/fig',
    message=FALSE,
    width = 100,
    comment = NA
  )
  knitr::knit_hooks$set(
    source = function(x, options) {
      paste("\\vspace{-1ex}",
            "\\begin{tikzCodeBlock}[listing style=sweavechunk]",
            paste(x, collapse = '\n'),
            "\\end{tikzCodeBlock}\n\n", sep = '\n')
    },
    output = function(x, options) {
      paste("\\vspace{-2ex}",
            "\\begin{Verbatim}[frame=single]",
            sub("\n+$", "", paste(x, collapse = '\n')),
            "\\end{Verbatim}",
            "",
            sep = '\n')
    },
    warning = function(x, options) {
      paste("\\vspace{-2ex}",
            "\\begin{Verbatim}[frame=single,formatcom=\\color{warningcolor}]",
            sub("\n+$", "", paste(strwrap(x, width = options$width),
                                  collapse = '\n')),
            "\\end{Verbatim}",
            "",
            sep = '\n')
    },
    chunk = function(x, options) x
  )
@



\title{TikZDevice: LaTeX Graphics for R}
\author{Charlie Sharpsteen and Cameron Bracken}
\date{\Sexpr{strftime(read.dcf(system.file('DESCRIPTION', package = 'tikzDevice'), fields = 'Date'), format = '%B %d, %Y')}}
\gdef\packageURL{\url{https://github.com/yihui/tikzDevice}}
\gdef\packageVersion{\Sexpr{tikzDevice:::getTikzDeviceVersion()}}

% Use the hyperref package to fill in PDF metadata.
\hypersetup{
  pdftitle=\thetitle,
  pdfauthor=\theauthor,
  pdfsubject={Manual for Version: \packageVersion, \thedate}
}


\begin{document}
% -----------------------------------------------------------------------------
%                                 Cover Page
% -----------------------------------------------------------------------------
<<tikzTitlePlot,results='hide'>>=
  tikz('figs/titlePlot.tex',width=4,height=4)

  x <- seq(-4.5,4.5,length.out=100)
  y <- dnorm(x)

  xi <- seq(-2,2,length.out=30)
  yi <- dnorm(xi)

  plot(x,y,type='l',col='blue',ylab='$p(x)$',xlab='$x$')
  lines(xi,yi,type='s')
  lines(range(xi),c(0,0))
  lines(xi,yi,type='h')
  title(main="$p(x)=\\frac{1}{\\sqrt{2\\pi}}e^{-\\frac{x^2}{2}}$")
  int <- integrate(dnorm,min(xi),max(xi),subdivisions=length(xi))
  text(2.8,0.3,paste(
    "\\small$\\displaystyle\\int_{",min(xi),"}^{",max(xi),"}p(x)dx",
    "\\approx",round(int[['value']],3),'$',sep=''))

  dev.off()
@

\begin{titlingpage}
  % NOTE:
  % Most dimensions and positions in this cover page were optimized for US
  % Letter stock size and so are given in inches. It may be useful to revise
  % this one day so that the layout is a bit more scalable.
  %
  % Use remember picture and overlay so that `current page` coordinates can be
  % accessed.
  \begin{tikzpicture}[remember picture, overlay]
    % Title and Info
    % --------------
    {\fontsize{60}{36}
    \node[below right = 0.5em of current page.north west,
      anchor = north east,
      rotate = 90,
      outer sep = 0pt,
      inner sep = 0pt
    ]
      (title)
      {\bfseries{\fontsize{36}{36}\selectfont\color{red}\TikZ}Device};
    }

    \draw[line width = 5pt] ([xshift = 7.5pt]title.base west) -- ([xshift = 7.5pt]title.base east);

    % Have to split subtitle, authors, etc. into several nodes because
    % apparently TikZ can't deal with font change commands and line breaks
    % existing in the same node. A bit of a pain because the value of
    % \baselineskip has to be twaddled by wrapping some \nodes in font
    % size descriptors.
    \node[right = 12.5pt of title.base east,
      anchor = north west,
      align = left,
      font = {\Huge\bfseries}
    ]
      (subtitle)
      {\LaTeX\ Graphics for \lang{R}};

    {\huge
    \node[below = \baselineskip of subtitle.base west,
      anchor = north west,
      align = left,
      font = {\LARGE}
    ]
      (authors)
      {%
        Charlie Sharpsteen\\
        Cameron Bracken%
      };
    }

    \node[right = 12.5pt of title.base west,
      anchor = base west,
      align = left
    ]
      (packageInfo)
      {%
        \thedate\\
        \packageURL%
      };

    {\LARGE
    \node[above = \baselineskip of packageInfo.north west,
      anchor = base west,
      align = left,
      font = {\LARGE\bfseries}
    ]
      (version)
      {Version: \packageVersion};
    }


    % Logo and Plot
    % -------------

    % Scaling the R logo to a width of 4.75 in was determed through trial and
    % error. The center of the image is shifted relative to the bottom right
    % corner of the page such that the point where the right leg of the "R"
    % glyph intersects the inside of the halo is sitting over the corner of the
    % page.
    \node[inner sep = 0pt,
      above left = 0.78in and 1.48in of current page.south east,
      anchor = center
    ]
      (Rlogo)
      {\includegraphics[width=4.75in]{img/Rlogo}};

    % This node contains an embedded `tikzpicture` environment produced by the
    % tikzTitlePlot code block.
    \node[anchor = north east,
      inner sep = 0pt
    ]
      (titlePlot) at (current page.north east)
      {\input{figs/titlePlot.tex}};


    % Connect Logo and Plot
    % ---------------------
    \node[below left = 0.325\stockheight and 0.325\stockwidth of current page.center]
      (midPointA) {};

    \node[below right = 0.125\stockheight and 0.125\stockwidth of current page.center]
      (midPointB) {};

    \tikzset{
      grow bigger/.style={decoration = {
        shape backgrounds,
        shape = dart,
        shape scaled,
        shape start size = 0.125cm,
        shape end size = 0.5cm,
        shape sep = {.25cm, between borders}
      }}
    }

    \path[decorate, grow bigger, fill = black!25]
      plot[smooth, tension = 1]
        coordinates{(Rlogo.190) (midPointA) (midPointB) (titlePlot.south)};

  \end{tikzpicture}
\end{titlingpage}


% -----------------------------------------------------------------------------
%                              Table of Contents
% -----------------------------------------------------------------------------
\frontmatter
  \tableofcontents*


\mainmatter


% -----------------------------------------------------------------------------
%                           Chapter 1: Introduction
% -----------------------------------------------------------------------------
\chapter{Introduction}

The \pkg{tikzDevice} package provides a graphics output device for \lang{R} that
records plots in a \LaTeX -friendly format. The device transforms plotting
commands issued by \lang{R} functions into \LaTeX\ code blocks. When included in a
paper typeset by \LaTeX , these blocks are interpreted with the help of
TikZ---a graphics package for \TeX\ and friends written by Till Tantau. By
allowing \LaTeX\ to handle typesetting of text in \lang{R} plots along with the
rest of the text in the paper the full power of \TeX\ is available to the
\lang{R} user. There are also no discontinuities in font selection and
typesetting as demonstrated by a comparison between \autoref{fig:pdf-example}
and \autoref{fig:tikz-example}.


% FIXME:
% This example is biased. It would be best to choose a TeX font for which AFM
% metrics are available and show how much of a pain in the ass it is to use the
% R `Type1Font` function vs. how easy it is to set tikzDevice options and let
% TeX do the heavy lifting.
\begin{figure}[!hb]
  \centering

  \begin{minipage}[t]{0.4\linewidth}
    \begin{tikzCodeBlock}[listing style=sweavechunk,
      code body/.append style={codebody color=white}]
pdf('pdf-example.pdf',
  width = 3.25, height = 3.25)
plot(1, 1, main = 'Hello!')
dev.off()
    \end{tikzCodeBlock}

<<pdf-example,echo=FALSE,results='hide'>>=
  pdf('figs/pdf-example.pdf', width = 3.25, height = 3.25)
  plot(1, 1, main = 'Hello!', ps = 10)
  dev.off()
@
    \includegraphics{figs/pdf-example}
    \caption{Output from \code{pdf()}}
    \label{fig:pdf-example}
  \end{minipage}
  \hspace{0.1\linewidth}
  \begin{minipage}[t]{0.4\linewidth}
    \begin{tikzCodeBlock}[listing style=sweavechunk,
      code body/.append style={codebody color=white}]
tikz('tikz-example.tex',
  width = 3.25, height = 3.25)
plot(1, 1, main = 'Hello \\TeX !')
dev.off()
    \end{tikzCodeBlock}

<<tikz-example,echo=FALSE,results='hide'>>=
  tikz('figs/tikz-example.tex', width = 3.25, height = 3.25)
  plot(1, 1, main = 'Hello \\TeX !')
  dev.off()
@
    \input{figs/tikz-example.tex}
    \caption{Output from \code{tikz()}}
    \label{fig:tikz-example}
  \end{minipage}
\end{figure}


This document is divided into three parts. \autoref{part:usage} describes the
package functionality and provides example usage. Besides the \lang{R}
environment, use of the \TikZ\ device requires the user to have a
working \LaTeX{} compiler along with an installed version of the \TikZ{}
package---version 2.00 or greater. \autoref{part:installation} of this
documentation offers suggestions on how to get these dependencies installed and
working properly.

\autoref{part:implementation} is intended for those who are curious as to the
details of how this package is implemented. This part attempts to explain how
the \pkg{tikzDevice} package does the things that it does and why it chooses to
do them that way. The authors have attempted to write this part of the
documentation in a way that is accessible to users as well as developers. This
information is provided in the hope that the \pkg{tikzDevice} may serve as a
case study for creating new \lang{R} graphics devices. This part of the
documentation may also help those considering undertaking the transition from
casual package-building to full-on hacking of the \lang{R} internals.

\section{Acknowledgements}

This package would not have been possible without the hard work and ingenuity
of many individuals. This package straddles the divide between two great open
source communities---the \lang{R} programming language and the \TeX{}
typesetting system. It is our hope that this work will make it easier for users
to leverage the strengths of both systems.

First off, we would like to thank the \lang{R} Core Team for creating such a
wonderful, open and flexible programming environment. Compared to other
languages we have used, creating packages and extensions for \lang{R} has
always been a liberating experience.

This package started as a fork of the Pic\TeX\ device created by Valerio Aimale
which is part of the \lang{R} core graphics system.  Without access to this
simple, compact example of implementing a graphics device we likely would have
abandoned the project in its infancy. We would also like to thank Paul Murrell
for all of his work on the \lang{R} graphics system and especially for his
research and documentation concerning the differences between the font systems
used by \TeX{} and \lang{R}.

This package also owes its existence to Friedrich Leisch's work on the
\pkg{Sweave} system and Roger D. Peng's \pkg{cacheSweave} extension. These
two tools got us interested in the concept of Literate Programming and
development of this package was driven by our desire to achieve a more seamless
union between our reports and our code.

The performance of this package is also enhanced by the database capabilities
provided by Roger D. Peng's \pkg{filehash} package. Without this package, the
approach to calculating font metrics taken by the \pkg{tikzDevice} would be
infeasible.

Last, but certainly not least, we would like to thank Till Tantau, Mark Wibrow
and the rest of the PGF/\TikZ\ team for creating the \LaTeX\ graphics package
that makes the output of this device meaningful. We would also like to express
deep appreciation for the beautiful documentation that has been created for the
\TikZ\ system.

As always, there are many more who have contributed in ways too numerous to
list.\\[\baselineskip]

\noindent Thank you!\\
\quad{\itshape ---The tikzDevice Team}

\nocite{murrellTex}
\nocite{rintern2009}
\nocite{tantau2008}
\nocite{peng2006}


\partimage{
 \node[above left = 1in of current page.south east,
   anchor = south east,
   scale = 1.25
 ]
   % This image is generated by an example in chapter 3.
   {\input{figs/latexEx}};
}
\part{Usage and Examples}
  \label{part:usage}


% -----------------------------------------------------------------------------
%                         Chapter 2: Package Loading
% -----------------------------------------------------------------------------
\chapter{Loading the Package}

The functions in the \pkg{tikzDevice} package are made accessible in the
\lang{R} environment by using \code{library()}:

\begin{Verbatim}[frame=single]
library(tikzDevice)
\end{Verbatim}

\noindent Upon loading, the package will search for the following \LaTeX\ compilers:

\begin{itemize}
  \item{\hologo{pdfLaTeX}}
  \item{\hologo{XeLaTeX}}
  \item{\hologo{LuaLaTeX}}
\end{itemize}

Access to \LaTeX\ is essential for the device to produce output as the compiler
is queried for font metrics when constructing plots that contain text. For more
information on why communication between the device and \LaTeX\ is necessary,
see \autoref{part:implementation}. The package will fail to load if
\hologo{pdfLaTeX} cannot be located. The presence of the \hologo{XeLaTeX} and
\hologo{LuaLaTeX} compilers is optional. When the package loads successfully,
a startup message will be printed that looks similar to the following:

\begin{Verbatim}[frame=single]
Loading required package: filehash
filehash: Simple key-value database (2.2 2011-07-21)
tikzDevice: R Graphics Output in LaTeX Format (v0.7)
  LaTeX found in the PATH using the command: pdflatex
  XeLaTeX found in the PATH using the command: xelatex
  LuaLaTeX found in the PATH using the command: lualatex
\end{Verbatim}

If a working \hologo{pdfLaTeX} compiler cannot be found, the \pkg{tikzDevice} package
will fail to load and a warning message will be displayed:

\begin{Verbatim}[frame=single]
Error : .onLoad failed in loadNamespace() for 'tikzDevice', details:
  call: fun(libname, pkgname)
  error:

An appropriate LaTeX compiler could not be found.
Access to LaTeX is required in order for the TikZ device
to produce output.

The following places were tested for a valid LaTeX compiler:

	the global option: tikzLatex
	the environment variable: R_LATEXCMD
	the environment variable: R_PDFLATEXCMD
	the global option: latexcmd
	the PATH using the command: pdflatex
	the PATH using the command: latex
	the PATH using the command: /usr/texbin/pdflatex

...

Error: loading failed
\end{Verbatim}

In this case, \pkg{tikzDevice} has done its very best to locate a working
compiler and came up empty.  If you have a working \LaTeX\ compiler, the next
section describes how to inform the \pkg{tikzDevice} package of its location.
For suggestions on how to obtain a \LaTeX\ compiler, see
\autoref{part:installation}.


\section{Options That Affect Package Behavior}
  \label{sec:options}

The \pkg{tikzDevice} package is influenced by a number of options that may be
set locally in your \lang{R} scripts or in the \lang{R} console or globally in
a \code{.Rprofile} file. All of the options can be set by using
\code{options(<option> = <value>)}. These options allow for the use of custom
\code{documentclass} declarations, \LaTeX\ packages, and typesetting engines
(e.g. \hologo{XeLaTeX} or \hologo{LuaLaTeX}).

For convenience the function \code{setTikzDefaults()} is provided which sets
all the global options back to their original values.

The proper placement of a \code{.Rprofile} file is explained in the \lang{R}
manual page \code{?Startup}. For the details of why calling the \LaTeX\ compiler is
necessary, see \autoref{part:implementation}.

A lot of power is given to you through these global options, and with great
power comes great responsibility. For example, if you do not include the
\TikZ\ package in the \code{tikzLatexPackages} option then all of the string
metric calculations will fail. Or if you use a different font when compiling
than you used for calculating metrics, strings may be placed incorrectly.
There are innumerable ways for packages to clash in \LaTeX\ so be aware.


\subsection{The \pkgopt{tikzDefaultEngine} Option}

This option specifies which typesetting engine the \pkg{tikzDevice} package
will prefer. Current possible values are \code{pdftex}, \code{xetex} or
\code{luatex} which will respectively trigger the use of the \hologo{pdfLaTeX},
\hologo{XeLaTeX} or \hologo{LuaLaTeX} compilers.

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(tikzDefaultEngine = 'pdftex')
\end{tikzCodeBlock}

\begin{tikzCodeBlock}[title={Choosing the \TeX\ engine},listing style=sweavechunk]
options(tikzDefaultEngine = 'xetex')
options(tikzDefaultEngine = 'luatex')
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzLatex}, \pkgopt{tikzXelatex} and \pkgopt{tikzLualatex} Options}

Specifies the location of the \LaTeX{}, \hologo{XeLaTeX} and \hologo{LuaLaTeX}
compilers to be used by \pkg{tikzDevice}. Setting a default for this option may
help the package locate a missing compiler:

\begin{tikzCodeBlock}[title={Setting default compilers in \code{.Rprofile}},listing style=sweavechunk]
options(tikzLatex = '/path/to/pdflatex')
options(tikzXelatex = '/path/to/xelatex')
options(tikzLualatex = '/path/to/lualatex')
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzMetricsDictionary} Option}

When using the graphics device provided by \pkg{tikzDevice}, you may notice
that \lang{R} appears to ``lag" or ``hang'' when commands such as \code{plot()}
are executed. This is because the device must query the \LaTeX\ compiler for
string widths and font metrics. For a normal plot, this may happen dozens or
hundreds of times---hence \lang{R} becomes unresponsive for a while. The good
news is that the \code{tikz()} code is designed to cache the results of these
computations so they need only be performed once for each string or character.
By default, these values are stored in a temporary cache file which is deleted
when \lang{R} is shut down. Using the option \code{tikzMetricsDictionary}, a
permanent cache file may be specified:

\begin{tikzCodeBlock}[title={Setting a location in \code{.Rprofile} for a permanent metrics dictionary},listing style=sweavechunk]
options(tikzMetricsDictionary = '/path/to/dictionary/location')
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzDocumentDeclaration} Option}

For \code{standAlone == TRUE}, \code{tikzDocumentDeclaration} also influences the
calculation of font metrics. If a base font size is specified as an option to
the document class, the \pkg{tikzDevice} will use this value as the base font
size for graphics.

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(tikzDocumentDeclaration = "\\documentclass[10pt]{article}")
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzLatexPackages}, \pkgopt{tikzXelatexPackages} and \pkgopt{tikzLualatexPackages} Options}

Character vectors. These are the packages which are included when using the
\code{standAlone} option as well as when font metrics are calculated. If you
use additional packages that affect fonts, such as \code{mathpazo}, or
additional \LaTeX\ macros, such as \code{amsmath}, these packages should be
added to this list.

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(
  tikzLatexPackages = c(
    "\\usepackage{tikz}",
    "\\usepackage[active,tightpage]{preview}",
    "\\PreviewEnvironment{pgfpicture}",
    "\\setlength\\PreviewBorder{0pt}")
  ),

  tikzXelatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,xetex]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
    "\\setlength\\PreviewBorder{0pt}\n"
  ),

  tikzLualatexPackages = c(
    "\\usepackage{tikz}\n",
    "\\usepackage[active,tightpage,psfixbb]{preview}\n",
    "\\usepackage{fontspec,xunicode}\n",
    "\\PreviewEnvironment{pgfpicture}\n",
    "\\setlength\\PreviewBorder{0pt}\n"
  )
)
\end{tikzCodeBlock}

\begin{tikzCodeBlock}[title={Adding a package that affects fonts},listing style=sweavechunk]
options( tikzLatexPackages = c(
  getOption( "tikzLatexPackages" ),
  "\\usepackage{mathpazo}"
))
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzMetricPackages} and \pkgopt{tikzUnicodeMetricPackages} Options}

Character vectors. These are the extra packages which are additionally loaded
when doing font metric calculations.  As you see below, the font encoding is
set to Type 1. This is very important so that character codes of \LaTeX\ and
\lang{R} match up. The Unicode metric packages are used when the \hologo{XeTeX}
or \hologo{LuaTeX} engines are in use.

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(
  tikzMetricPackages = c(
    "\\usepackage[T1]{fontenc}\n",
    "\\usetikzlibrary{calc}\n"
  ),

  tikzUnicodeMetricPackages = c(
    "\\usepackage[T1]{fontenc}\n",
    "\\usetikzlibrary{calc}\n",
    "\\usepackage{fontspec,xunicode}\n"
  )
)
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzFooter} Option}

A character vector. This footer is appended to the end of the figure when
\code{standAlone==TRUE} before the \verb|\end{document}| statement.

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(tikzFooter = "")
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzSanitizeCharacters} and \pkgopt{tikzReplacementCharacters} Options}

\code{tikzSanitizeCharacters} is a character vector of special \LaTeX
characters to replace while \code{tikzReplacementCharacters} is a character
vector containing the corresponding replacements.

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(
  tikzSanitizeCharacters = c('%','$','}','{','^','_','#','&','~'),
  tikzReplacementCharacters = c('\\%','\\$','\\}','\\{','\\^{}','\\_{}',
    '\\#','\\&','\\char`\\~')
)
\end{tikzCodeBlock}


\subsection{The \pkgopt{tikzLwdUnit} Option}

Originally, 1 unit of line width in \lang{R} was translated to 0.4~pt.
This results in lines that are thinner than with default graphics
or with the PDF device.
This option controls the translation factor~-- use \code{72.27 / 96}
for compatibility with the \lang{R} default
(96 pixels in \lang{R} is 1 inch, which is 72.27 points in \TeX{}).

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(tikzLwdUnit = 72.27 / 96)
\end{tikzCodeBlock}


\subsection{The deprecated \pkgopt{tikzRasterResolution} Option}

When \code{tikz} is requested to add a raster to a graphic, the raster is
written to a PNG file which is then included by the \LaTeX\ code.
In the current version, the raster is always written ``as is''
(after mirroring has been applied) using \code{png::writePNG()}
\citep{urbanek2013}.
No resampling or transformation of any kind are applied in this process,
rotation and interpolation are carried out by \LaTeX.


\subsection{The \pkgopt{tikzPdftexWarnUTF} Option}

A \code{TRUE/FALSE} value that controls whether warnings are printed if
Unicode characters are sent to a device using the \hologo{pdfTeX} engine.

\begin{tikzCodeBlock}[title={Default},listing style=sweavechunk]
options(tikzPdftexWarnUTF = TRUE)
\end{tikzCodeBlock}


% -----------------------------------------------------------------------------
%                       Chapter 3: The tikz Function
% -----------------------------------------------------------------------------
\chapter{The \code{tikz} Function}

\section{Description}

The \code{tikz} function provides most of the functionality of the
\pkg{tikzDevice} package. This function opens an \lang{R} graphics device that
records plots as a series of \TikZ\ commands. The device supports many levels
of output that range from stand-alone \LaTeX\ documents that may be compiled
into figures to code chunks that must be incorporated into existing \LaTeX\
documents using the \verb`\include{}` macro.


\section{Usage}

The \code{tikz} function opens a new graphics device and may be called with
the following arguments:

<<tikzArgs>>=
formatR::usage(tikz)
@

\begin{flexlabelled}{code}{*}{0.5em}{0.5em}{*}{\leftmargin}
  \item[file]
    A character string indicating the desired path to the output file. It is
    recommended, but not required, that the filename end in \code{.tex}.

  \item[width]
    The width of the output figure, in \emph{inches}.

  \item[height]
    The height of the output figure, in \emph{inches}.

  \item[onefile]
    Controls whether output should be directed to a single file containing one
    \code{tikzpicture} environment per plot or split into multiple files each
    containing a single \code{tikzpicture} environment.

  \item[bg]
    The starting background color for the plot.

  \item[fg]
    The starting foreground color for the plot.

  \item[pointsize]
    Base pointsize used in the LaTeX document.  This option is only referenced
    if a valid pointsize cannot be extracted from the value of
    \code{getOption("tikzDocumentDeclaration")}.  See \autoref{subsec:fontCalc}
    for more details.

  \item[lwdUnit]
    The number of \code{pt}s in LaTeX that \code{lwd=1} in R is translated to.
    Defaults to 0.4 (LaTeX and TikZ default); for compatibility with R default,
    please use 72.27/96 (96 pixels in R is 1 inch, which is 72.27 points in TeX).
    See also \autoref{sec:options}, ``Options That Affect Package Behavior.''

  \item[standAlone]
    A logical value indicating whether the resulting file should be suitable
    for direct processing by \LaTeX.

  \item[bareBones]
    A logical value indicating whether \TikZ\ code is produced without being
    placed within a \code{tikzpicture} environment.

  \item[console]
    Controls whether output is directed to the \lang{R} console. This is useful
    for dumping \TikZ\ output directly into a \LaTeX\ document via sink. If
    \code{TRUE}, the \code{file} argument is ignored. Setting \code{file=\'{}\'{}} is
    equivalent to setting \code{console=TRUE}.

  \item[sanitize]
    Should special latex characters be replaced (Default \code{FALSE}). See
    \autoref{sec:options}, ``Options That Affect Package Behavior''
    for which characters are replaced.

  \item[engine]
    A string specifying which \TeX{} engine to use. Possible values are
    \code{'pdftex'}, \code{'xetex'} and \code{'luatex'}.

  \item[documentDeclaration]
    See \autoref{sec:options}, ``Options That Affect Package Behavior.''

  \item[packages]
    See \autoref{sec:options}, ``Options That Affect Package Behavior.''

  \item[footer]
    See \autoref{sec:options}, ``Options That Affect Package Behavior.''
\end{flexlabelled}

The first six options should be familiar to anyone who has used the default
graphics devices shipped with \lang{R}. The options \code{standAlone}
and \code{bareBones} are specific to the \code{tikz()} graphics device and
affect the structure the output file. Using these options \code{tikz}
supports three modes of output:

\begin{itemize}
  \item
    Graphics production as complete \LaTeX\ files suitable for compilation.

  \item
    Graphics production as complete figures suitable for inclusion in \LaTeX\
    files.

  \item
    Graphics production as raw figure code suitable for inclusion in an
    enclosing \code{tikzpicture} environment in a \LaTeX\ file.
\end{itemize}


\section{Font Size Calculations}
  \label{subsec:fontCalc}

The overarching goal of the \pkg{tikzDevice} is to provide seamless integration
between text in \lang{R} graphics and the text of \LaTeX\ documents that contain those
graphics. In order to achieve this integration the device must translate font
sizes specified in \lang{R} to corresponding font sizes in \LaTeX. The issue is
that font sizes in \LaTeX\ are controlled by a ``base font size'' that is
specified at the beginning of the document---typically 10pt. There is no easy
way in \LaTeX\ to change the font size to a new numerical value, such as 16pt
for a plot title. Fortunately, the \TikZ\ graphics system allows text to be
resized using a scaling factor. The \pkg{tikzDevice} calculates a scaling
factor used to approximate other font sizes using the following three inputs:

\begin{itemize}
  \item
    The ``base font size'' specified when the graphics device is created.

  \item
    The ``character expansion factor'' parameter, specified using the `cex'
    argument to functions such as described in the documentation of the \lang{R}
    function \code{par}.

  \item
    The ``font size'' parameter, specified using the `ps' argument to functions
    such as \code{par} or the `fontsize' argument to functions such as
    \code{gpar}.
\end{itemize}

The calculation used is:

\[
  \mbox{Scaling Factor} = \mbox{cex} \cdot \frac{\mbox{ps}}{\mbox{base font size}}
\]

The tricky bit is the specification of the ``base font size''. By default the
\pkg{tikzDevice} will attempt to determine this parameter by scanning the value of
\code{options( "tikzDocumentDeclaration" )} using the regular expression
\code{\textbackslash d+pt}. With the default header:
\[
  \mbox{\code{\textbackslash documentclass[10pt]\{article\}}}
\]
this regular expression will return 10 as the base pointsize to be used by the
device. If the regular expression fails to produce a match, the value of the
\code{pointsize} argument to the \code{tikz} function will be used.


\subsection{UTF-8 Output}

Version 0.6.0 of the \pkg{tikzDevice} introduced support for (multibyte)
Unicode characters in the text of graphics through support for \hologo{XeTeX}.
Version 0.7.0 extended multilingual typesetting further by adding support for
the \hologo{LuaTeX} compiler. Unicode support in \pkg{tikzDevice} is subject to
a few important caveats:

\begin{description}
  \item[System Requirements:]
    A working version of \hologo{XeLaTeX} or \hologo{LuaLaTeX}  along with the
    packages \code{fontspec} and \code{xunicode} are required for direct
    processing of Unicode input. If \pkg{tikzDevice} cannot find a Unicode-aware
    compiler, then Unicode support cannot be guaranteed.

  \item[Encoding:]
    \pkg{tikzDevice} will try its best to convert characters from other
    encodings but do not count on it converting things correctly, best to do
    the conversion yourself beforehand to avoid unexpected output.

  \item[Fonts:]
    Having a Unicode character actually show up in your \LaTeX\ document relies
    on the font you use having the glyph available. We leave it up to the user
    to know for themselves what is available.  Otherwise you will likely just
    get no output in place of where the character should be.

  \item[Plotmath:]
    There is specifically no support for input of plotmath characters as
    unicode since the user can simply input \LaTeX\ math directly. We strongly
    encourage the use of \LaTeX\ math over plotmath for style and consistency's
    sake.  A consequence of this is that most of the \lang{R} examples and demos
    of plotmath won't work without significant manipulation (your mileage may
    vary but you may get anything from errors to warnings to documents that
    mysteriously won't compile). That is not to say that the output could not
    be duplicated with \pkg{tikzDevice} but the examples will not work out of
    the box.

  \item[Compiling:]
    A graphic that contains UTF-8 characters should be compiled with
    \hologo{XeLaTeX} or \hologo{LuaLaTeX} with the \code{xunicode} and
    \code{fontspec} packages enabled.

  \item[ASCII only:]
    Everything should be exactly the same as previous versions if only ASCII
    (single byte) characters are used (i.e. character codes less than 132).
\end{description}



\section{Examples}

\subsection{Default Mode}

The most common use of the \code{tikz} function is to produce a plot that
will be included in another \LaTeX\ document, such as a report. Running the
following example in \lang{R} will produce a very simple graphic using the
\code{plot} function:

<<simpleEx,echo=TRUE,results='hide'>>=
library(tikzDevice)
tikz('figs/simpleEx.tex',width=3.5,height=3.5)
plot(1,main='Hello World!')
dev.off()
@

A \LaTeX\ document is then required to display the figure.  This document must
include \TikZ\ as one of the packages that it loads. \TikZ\ provides several
libraries that enable additional functionality, however none of these libraries
are currently required to use the output of \code{tikz}. Inside the \LaTeX\
document, the contents of the file \code{simpleEx.tex} are imported using the
\verb|\include| command.

\begin{figure}[!htbp]
  \centering

  \begin{minipage}{0.5\textwidth}
    \begin{tikzCodeBlock}[title={Example \LaTeX{} Document},listing style=latexsource,code body/.append style={codebody color=white}]
\documentclass{article}

% All LaTeX documents including
% tikz() output must use this
% package!
\usepackage{tikz}

\begin{document}
  \begin{figure}[!ht]
    \centering

    % The output from tikz()
    % is imported here.
    \input{simpleEx.tex}

    \caption{Simple Example}
  \end{figure}
\end{document}
    \end{tikzCodeBlock}
  \end{minipage}
  \hfill
  \begin{minipage}{0.45\textwidth}
    \input{figs/simpleEx.tex}
  \end{minipage}
  \caption{Example of simple \code{tikz} usage.}
\end{figure}

One of the most exciting aspects of the \code{tikz} function is that the
inclusion of arbitrary \LaTeX\ code is allowed in strings passed to  plotting
commands. An important issue to note is that many \LaTeX\ commands are prefixed
by the backaslash character: \textbackslash. Unfortunately, in many programming
languages, the backslash character is also given a special status when it
appears in strings. Therefore, it is necessary to place two backslashes,
\textbackslash\textbackslash, in \lang{R} strings in order to cause backslash to
appear in the output for \LaTeX. The next example demonstrates how to use
\LaTeX\ commands in plot annotation.


\begin{figure}[!htbp]
  \centering
  \begin{minipage}{0.5\textwidth}
<<latexEx,echo=TRUE,results='hide',tidy=FALSE>>=
library(tikzDevice)
tikz('figs/latexEx.tex',
  width=3.5,height=3.5)

x <- rnorm(10)
y <- x + rnorm(5,sd=0.25)

model <- lm(y ~ x)
rsq <- summary( model )$r.squared
rsq <- signif(rsq,4)

plot(x, y, main='Hello \\LaTeX!')
abline(model, col='red')

mtext(paste("Linear model: $R^{2}=",
  rsq, "$"), line=0.5)

legend('bottomright', legend =
  paste("$y = ",
    round(coef(model)[2],3), 'x +',
    round(coef(model)[1],3), '$',
    sep = ''), bty = 'n')

dev.off()
@
  \end{minipage}
  \hfill
  \begin{minipage}{0.45\textwidth}
    \input{figs/latexEx.tex}
  \end{minipage}
  \caption{A more complicated example of \code{tikz} usage incorporating
    natively rendered \LaTeX\ commands.}
\end{figure}


\subsection{\pkgopt{bareBones} Mode}

\code{bareBones} output is designed to facilitate inclusion of code generated
by \code{tikz} into a larger \TikZ\ graphic. Normally \code{tikz} wraps output
as a self-contained \code{tikzpicture} environment. When \code{bareBones} is
invoked, the wrapping environment is omitted. This option allows output to be
embedded inside another \code{tikzpicture} of the user's own construction.

<<bareBonesExample,echo=TRUE,results='hide',tidy=FALSE>>=
library(tikzDevice)
library(maps)

tikz('figs/westCoast.tex', bareBones=TRUE)

map('state', regions=c('california', 'oregon', 'washington'),
    lwd=4, col='grey40')

# Insert some named coordinates into the picture that will
# be available once the picture is included into the
# TeX document.
tikzCoord(-124.161, 40.786, 'humBay')
tikzCoord(-122.962, 46.148, 'longView')
tikzCoord(-124.237, 43.378, 'coosBay')
tikzCoord(-122.419, 37.775, 'sfBay')

dev.off()
@

The \verb|\include| command may now be used to import the device output into
another \code{tikzpicture}. The included code must be wrapped in a \code{scope}
environment that contains the options \code{x=1pt} and \code{y=1pt}. This
informs \TikZ\ of the units being used in the coordinates of the plot output.
The options \code{xshift} and \code{yshift} may also be applied to the
\code{scope} in order to position the plot. The following code demonstrates how
to embed \code{bareBones} output in a \code{tikzpicture}:

\begin{tikzCodeBlock}[title={Example of a \TikZ{} environment including \code{bareBones} output},
  code body/.append style={codebody color=white},
  listing style=latexsource]
\begin{tikzpicture}

  % Include bareBones output inside a scope with x and y units set to 1pt
  \begin{scope}[x=1pt,y=1pt]
    \input{figs/westCoast}
  \end{scope}

  % Label ports using coordinates placed into the barBones output by the
  % tikzAnnotate function.
  \foreach \name/\port in {
    Longview/longView,
    Coos Bay/coosBay,
    Humboldt Bay/humBay,
    Oakland/sfBay%
  } {
    \node[circle, draw, ultra thick, fill=green!60!brown!40,
      outer sep=6pt,minimum size=12pt,
      pin={[draw, ultra thick,
        rounded corners,
        pin edge={black, ultra thick, <-, >=stealth}
      ] 180 : \name}] at (\port) {};
  }

\end{tikzpicture}
\end{tikzCodeBlock}


\begin{figure}[!htbp]

  \centering

  \begin{tikzpicture}

    \begin{scope}[x=1pt,y=1pt]
      \input{figs/westCoast}
    \end{scope}

    \foreach \name/\port in {
      Longview/longView,
      Coos Bay/coosBay,
      Humboldt Bay/humBay,
      Oakland/sfBay%
    } {
      \node[circle, draw, ultra thick, fill=green!60!brown!40,
        outer sep=6pt,minimum size=12pt,
        pin={[draw, ultra thick,
          rounded corners,
          pin edge={black, ultra thick, <-, >=stealth}
        ] 180 : \name}] at (\port) {};
    }

  \end{tikzpicture}

  \caption{A \TikZ\ drawing with embedded output from \code{tikz(bareBones=TRUE)}.}
\end{figure}

\subsection{\pkgopt{standAlone} Mode}

When the \code{standAlone} option is passed to \code{tikz}, the resulting
\code{.tex} file will be a complete \LaTeX\ document that can be compiled into
a stand-alone figure. This means that in addition to \verb|\begin{tikzpicture}|
and \verb|\end{tikzpicture}| the file will also contain \verb|\begin{document}|,
\verb|\end{document}| and a \LaTeX\ preamble. The \code{preview} package is also
used in files produced by \code{standAlone} to crop the pages in the resulting
document to the bounding boxes of the plots.  Stand-alone output may be
produced in the following manner:

<<standAloneExample,echo=TRUE,results='hide',tidy=FALSE>>=
library(tikzDevice)
tikz('standAloneExample.tex',standAlone=TRUE)
plot(sin,-pi,2*pi,main="A Stand Alone TikZ Plot")
dev.off()
@


<<standAloneCompileExample, results='hide', eval=FALSE>>=

  library(tools)

  catch <- system(paste(Sys.which('pdflatex'),
    '-interaction=batchmode -output-directory figs/ figs/standAloneExample.tex'),
    ignore.stderr=T)

  # If compiling the example failed, we don't want to include a broken link.
  if( catch == 0 ){
    pdfLink <- "The file \\\\code{standAloneExample.tex} may then be compiled to produce
      \\\\href{./figs/standAloneExample.pdf}{standAloneExample.pdf}. "
  }else{
    pdfLink <- ""
  }
    #%\Sexpr{print(pdfLink)}
@

Note that files produced using the \code{standAlone} option should not be
included in \LaTeX\ documents using the \verb|\input| command! Use
\verb|\includegraphics| or load the \code{pdfpages} package and use
\verb|\includepdf|.


\subsection{\pkgopt{console} output Mode}

Version 0.5.0 of \pkg{tikzDevice} introduced the \code{console} option. With
this option, \code{tikz} will send output to \code{stdout} instead of a file.
This kind of output can be redirected to a file with \code{sink} or spit out
directly into a \TeX\ document from a \pkg{Sweave} file so that the \TeX\ file
is self contained and does not include other files via \verb|\input|.
(Including the chunk option \code{strip.white=FALSE} was necessary for some
versions of \pkg{tikzDevice} prior to 0.7.2.)

\tikzCodeInput[title={Catching \code{tikz} output inside Sweave},listing style=sweavechunk]{consoleExample}


\subsection{Using \hologo{XeLaTeX}}

It is also possible to use other typesetting engines like \hologo{XeLaTeX} by
using the global options provided by \pkg{tikzDevice}. The following example
was inspired by Dario Taraborelli and his article
\href{http://nitens.org/taraborelli/latex}{The Beauty of LaTeX}.

% `eval` normally set to `FALSE` as this example takes a long time to run and the
% required fonts are only availble by default on OS X.
<<xelatexFontVariantExample,tidy=FALSE,echo=TRUE,eval=FALSE,results='hide'>>=
# Set options for using XeLaTeX font variants.
options(tikzXelatexPackages = c(
  getOption('tikzXelatexPackages'),
  "\\usepackage[colorlinks, breaklinks]{hyperref}",
  "\\usepackage{color}",
  "\\definecolor{Gray}{rgb}{.7,.7,.7}",
  "\\definecolor{lightblue}{rgb}{.2,.5,1}",
  "\\definecolor{myred}{rgb}{1,0,0}",
  "\\newcommand{\\red}[1]{\\color{myred} #1}",
  "\\newcommand{\\reda}[1]{\\color{myred}\\fontspec[Variant=2]{Zapfino}#1}",
  "\\newcommand{\\redb}[1]{\\color{myred}\\fontspec[Variant=3]{Zapfino}#1}",
  "\\newcommand{\\redc}[1]{\\color{myred}\\fontspec[Variant=4]{Zapfino}#1}",
  "\\newcommand{\\redd}[1]{\\color{myred}\\fontspec[Variant=5]{Zapfino}#1}",
  "\\newcommand{\\rede}[1]{\\color{myred}\\fontspec[Variant=6]{Zapfino}#1}",
  "\\newcommand{\\redf}[1]{\\color{myred}\\fontspec[Variant=7]{Zapfino}#1}",
  "\\newcommand{\\redg}[1]{\\color{myred}\\fontspec[Variant=8]{Zapfino}#1}",
  "\\newcommand{\\lbl}[1]{\\color{lightblue} #1}",
  "\\newcommand{\\lbla}[1]{\\color{lightblue}\\fontspec[Variant=2]{Zapfino}#1}",
  "\\newcommand{\\lblb}[1]{\\color{lightblue}\\fontspec[Variant=3]{Zapfino}#1}",
  "\\newcommand{\\lblc}[1]{\\color{lightblue}\\fontspec[Variant=4]{Zapfino}#1}",
  "\\newcommand{\\lbld}[1]{\\color{lightblue}\\fontspec[Variant=5]{Zapfino}#1}",
  "\\newcommand{\\lble}[1]{\\color{lightblue}\\fontspec[Variant=6]{Zapfino}#1}",
  "\\newcommand{\\lblf}[1]{\\color{lightblue}\\fontspec[Variant=7]{Zapfino}#1}",
  "\\newcommand{\\lblg}[1]{\\color{lightblue}\\fontspec[Variant=8]{Zapfino}#1}",
  "\\newcommand{\\old}[1]{",
  "\\fontspec[Ligatures={Common, Rare},Variant=1,Swashes={LineInitial, LineFinal}]{Zapfino}",
  "\\fontsize{25pt}{30pt}\\selectfont #1}%",
  "\\newcommand{\\smallprint}[1]{\\fontspec{Hoefler Text}
    \\fontsize{10pt}{13pt}\\color{Gray}\\selectfont #1}"
))

# Set the content using custom defined commands
label <- c(
  "\\noindent{\\red d}roo{\\lbl g}",
  "\\noindent{\\reda d}roo{\\lbla g}",
  "\\noindent{\\redb d}roo{\\lblb g}",
  "\\noindent{\\redf d}roo{\\lblf g}\\\\[.3cm]",
  "\\noindent{\\redc d}roo{\\lblc g}",
  "\\noindent{\\redd d}roo{\\lbld g}",
  "\\noindent{\\rede d}roo{\\lble g}",
  "\\noindent{\\redg d}roo{\\lblg g}\\\\[.2cm]"
)

# Set the titles using custom defined commands, and hyperlinks
title <- c(
paste(
  "\\smallprint{D. Taraborelli (2008),",
  "\\href{http://nitens.org/taraborelli/latex}",
  "{The Beauty of \\LaTeX}}"
), paste(
  "\\smallprint{\\\\\\emph{Some rights reserved}.",
  "\\href{http://creativecommons.org/licenses/by-sa/3.0/}",
  "{\\textsc{cc-by-sa}}}"
))

# Draw the graphic
tikz('xelatexEx.tex',
  standAlone=TRUE,width=5,height=5,
  engine = 'xetex')
lim <- 0:(length(label)+1)
plot(lim,lim,cex=0,pch='.',xlab = title[2],ylab='', main = title[1])
for(i in 1:length(label))
  text(i,i,label[i])
dev.off()
@

Compiling the resulting file with \hologo{XeLaTeX} will produce the output in
\autoref{fig:xelatex}. Please note some of the fonts used in the example may
not be available on every system.

\begin{figure}[!ht]
\centering
\includegraphics{img/xelatexEx.pdf}
\caption{Result of \hologo{XeLaTeX} example}\label{fig:xelatex}
\end{figure}


\subsection{Annotating Graphics with \TikZ\ Commands}

The function \code{tikzAnnotate} provides the ability to annotate you graphics
with \TikZ\ commands.  There are a lot of exciting possibilities with this
feature---it basically opens up the door for you to draw anything on your plot
that can be drawn with \TikZ. Check out the results in
\autoref{fig:annotation}.

<<annotation,echo=TRUE,results='hide',tidy=FALSE>>=
library(tikzDevice)

# Load some additional TikZ libraries
tikz("figs/annotation.tex",width=4,height=4,
  packages = c(getOption('tikzLatexPackages'),
    "\\usetikzlibrary{decorations.pathreplacing}",
    "\\usetikzlibrary{positioning}",
    "\\usetikzlibrary{shapes.arrows,shapes.symbols}")
)

p <- rgamma (300 ,1)
outliers <- which( p > quantile(p,.75)+1.5*IQR(p) )
boxplot(p)

# Add named coordinates that other TikZ commands can hook onto
tikzCoord(1, min(p[outliers]), 'min outlier')
tikzCoord(1, max(p[outliers]), 'max outlier')

# Use tikzAnnotate to insert arbitrary code, such as drawing a
# fancy path between min outlier and max outlier.
tikzAnnotate(c("\\draw[very thick,red,",
  # Turn the path into a brace.
  'decorate,decoration={brace,amplitude=12pt},',
  # Shift it 1em to the left of the coordinates
  'transform canvas={xshift=-1em}]',
  '(min outlier) --',
  # Add a node with some text in the middle of the path
  'node[single arrow,anchor=tip,fill=white,draw=green,',
  'left=14pt,text width=0.70in,align=center]',
  '{Holy Outliers Batman!}', '(max outlier);'))

# tikzNode can be used to place nodes with customized options and content
tikzNode(
  opts='starburst,fill=green,draw=blue,very thick,right=of max outlier',
  content='Wow!'
)

dev.off()
@

\begin{figure}[!ht]
\centering
\input{figs/annotation.tex}
\caption{An example using \TikZ\ annotation.}\label{fig:annotation}
\end{figure}

\begin{landscape}

\subsection{\pkgopt{tikz} vs. \pkgopt{pdf} for \pkgopt{plotmath} symbols and Unicode characters}

This is a side-by-side example showing how \code{tikz(..., engine = 'xetex')} handles UTF-8
characters and plotmath symbols compared to the standard \lang{R} \code{pdf} device.

\begin{figure}[!ht]
\centering
  \begin{minipage}{4.25in}
    \includegraphics[width=4.25in]{img/plotmathDefault.pdf}
    \caption{\code{example(text)} using the standard \code{pdf()} device.}\label{fig:plotmathDefault}
  \end{minipage}
  \vspace{1em}
  \begin{minipage}{4.25in}
    \includegraphics[width=4.25in]{img/plotmathTikz.pdf}
    \caption{\code{example(text)} using \code{tikz(..., engine = 'xetex')}.}\label{fig:plotmathTikz}
  \end{minipage}
\end{figure}

\end{landscape}


% -----------------------------------------------------------------------------
%                      Chapter 4: The Metrics Functions
% -----------------------------------------------------------------------------
\chapter{The \code{getLatexCharMetrics} and \code{getLatexStrWidth} Functions}

\section{Description}

These two functions may be used to retrieve font metrics through the interface
provided by the \pkg{tikzDevice} package. Cached values of the metrics are
returned if they have been calculated by the \pkg{tikzDevice} before. If no
cached values exist, a \LaTeX\ compiler will be invoked to generate them.

\section{Usage}

The font metric functions are called as follows:

\begin{Verbatim}[frame=single]
getLatexStrWidth( texString, cex = 1, face= 1)

getLatexCharMetrics( charCode, cex = 1, face = 1 )
\end{Verbatim}

\begin{flexlabelled}{code}{*}{0.5em}{0.5em}{*}{\leftmargin}
  \item[texString]
    A string for which to compute the width. \LaTeX\ commands may be used in
    the string, however all backslashes will need to be doubled.

  \item[charCode]
    An integer between 32 and 126 which indicates a printable character in the
    ASCII symbol table using the T1 font encoding.

  \item[cex]
    The character expansion factor to be used when determining metrics.

  \item[face]
    An integer specifying the \lang{R} font face to use during metric
    calculations. The accepted values are as follows:

    \begin{description}
      \item[1:]
        Text should be set in normal font face.
      \item[2:]
        Text should be set in {\bfseries bold font face}.
      \item[3:]
        Text should be set in {\itshape italic font face}.
      \item[4:]
        Text should be set in {\bfseries\itshape bold italic font face}.
      \item[5:]
        Text should be interpreted as \code{plotmath} symbol characters.
        Requests for font face 5 are currently ignored.
    \end{description}
\end{flexlabelled}

\section{Examples}

The \code{getLatexStrWidth} function may be used to calculate the width of
strings containing fairly arbitrary \LaTeX\ commands. For example, consider
the following calculations:


<<strWidthDemo,echo=T>>=
getLatexStrWidth( "The symbol: alpha" )
getLatexStrWidth( "The symbol: $\\alpha$" )
@

For the first calculation, the word ``alpha'' was interpreted as just a word and
the widths of the characters `a', `l', `p', `h' and `a' were included in the
string width. For the second string, \verb|\alpha| was interpreted as a
mathematical symbol and only the width of the symbol `$\alpha$' was included in
the string width.

The \code{getLatexCharWidth} function must be passed an integer corresponding
to an ASCII character code and returns three values:

\begin{itemize}
  \item
    The \code{ascent} of the character. This is the distance between the
    baseline and the highest point of the character's glyph.

  \item
    The \code{descent} of the character. This is the distance between the baseline and
    the lowest point of the character's glyph.

  \item
    The width of the character.
\end{itemize}

The character `y' has an \code{ASCII} symbol code of 121 and possesses a tail
that descends below the text line. Therefore a non-zero value will be returned
for the descent of `y'. The character `x', \code{ASCII} code 120, has no
descenders, so its descent will be returned as zero.

<<charMetricDemo,echo=T,tidy=FALSE>>=
# Get metrics for 'y'
getLatexCharMetrics(121)

# Get metrics for 'x' - the second value is the descent
# and should be zero or very close to zero.
getLatexCharMetrics(120)
@

Note that characters, along with numbers outside the range of [32--126], may not
be passed to the \nolinebreak\code{getLatexCharMetrics}  function. If for
some reason a floating point number is passed, it will be floored through
conversion by \code{as.integer}.

<<charMetricErrors,echo=T,tidy=FALSE>>=
getLatexCharMetrics('y')
getLatexCharMetrics(20)

# Will return metrics for 'y'
getLatexCharMetrics(121.99)
@



\part{Installation Guide}
  \label{part:installation}

\chapter{Obtaining a \LaTeX\ Distribution}

This section offers pointers on how to obtain a \LaTeX\ distribution if there
is not one already installed on your system. The distributions detailed in this
section are favorites of the \pkg{tikzDevice} developers as they provide integrated
package managers which greatly simplify the process of installing additional
\LaTeX\ packages. Currently this section is not, and may never be, a
troubleshooting guide for \LaTeX\ installation. For those unfortunate
situations we refer the user to the documentation of each distribution.

A \LaTeX\ distribution provides the packages and support programs required by
the \pkg{tikzDevice} and the documents that use its output. In addition to a
\LaTeX\ compiler, a few extension packages are required.
\autoref{tikz:required} describes how to obtain and install these packages.

\section{Windows}

Windows users will probably prefer the MiKTeX distribution available at
\url{http://www.miktex.org}. An amazing feature of the MiKTeX distribution is
that it contains a package manager that will attempt to install missing
packages on-the-fly. Normally when \LaTeX\ is compiling a document that tries
to load a missing package it will wipe out with a warning message. When the
MiKTeX compilers are used compilation will be suspended while the new package
is downloaded.

% Perhaps a mention of the new portable MiKTeX distribution that can be run off
% of a thumbdrive? I haven't used it yet so I don't feel qualified to discuss it at this
% time.


\section{UNIX/Linux}

For users running a Linux or UNIX operating system, we recommend the TeX Live
distribution which is available at
\url{http://www.tug.org/texlive/acquire.html}. TeX Live is maintained by the
TeX Users Group and a new version is released every year.
We recommend using TeX Live 2008 or higher as the \code{tlmgr} package
manager was introduced in the 2008 distribution. Using \code{tlmgr} greatly
simplifies the adding and removing packages from the distribution. The website
offers an installation package, called \code{install-tl.tar.gz} or something
similar, that contains a shell script that can be used to install an up-to-date
version of the TeX Live distribution.
Note that the version
of TeX Live provided by many Linux package management systems sometimes
lags behind the version provided directly by the TeX Users Group.

\section{Mac OS X}

For users running Apple's OS X, we recommend the Mac TeX package available at
\url{http://www.tug.org/mactex/}. Mac TeX is basically TeX Live packaged inside
a convenient OS X installer along with a few add-on packages. One striking
difference between the Mac TeX and TeX Live installers is that the installer
for Mac TeX includes the whole TeX Live distribution in the initial download-
for TeX Live 2013 this amounts to approximately 2.3 GB. This is quite a large
download that contains several packages that the average or even advanced user
will never ever use. To conserve time and space we recommend installing from
the basic installer at \url{http://www.tug.org/mactex/morepackages.html} and
using the \code{tlmgr} utility to add desired add-on packages.

Adam R. Maxwell has created a very nice graphical interface to \code{tlmgr} for
OS X called the TeX Live Utility. It may be obtained from
\url{http://code.google.com/p/mactlmgr/} and we highly recommend it.


\section{Installing \TikZ\ and Other Packages}
  \label{tikz:required}

Unsurprisingly, \pkg{tikzDevice} requires the \TikZ\ package to be installed
and available in order to function properly. \TikZ\ is an abstraction of a
lower-level graphics language called \lang{PGF} and both are distributed as the
the \code{pgf} package. Users who do no have a full \TeX\ installation will
also need to install a few more required packages:

\begin{flexlabelled}{pkg}{0pt}{0.5em}{0.5em}{*}{\leftmargin}

    \item[pgf]{As mentioned, provides \TikZ.}
    \item[preview]{Used to crop documents in order to produce standalone figures.}
    \item[ms]{Martin Schröder's LaTeX packages. \code{everyshi.sty} lets us run commands at every shipped page.}
    \item[graphics]{\hologo{LaTeX}'s general-purpose graphics inclusion functionality.}
    \item[pdftex-def]{Device-specific colour and graphics definitions when running \hologo{pdfTeX}/\hologo{pdfLaTeX}.}
    \item[oberdiek]{\code{infwarerr.sty} provides info/error/warning messages}
    \item[ec]{(Font metrics for) the default font, European Computer Modern.}
    \item[xcolor]{Used by \TikZ\ to specify colors.}
    \item[fontspec]{Used by \hologo{LuaTeX} and \hologo{XeTeX} to select fonts.}
    \item[xunicode]{Assists \hologo{LuaTeX} and \hologo{XeTeX} with UTF-8 characters.}

\end{flexlabelled}


\subsection{Using a \LaTeX\ Package Manager}

The easiest way to install \LaTeX\ packages is by using a distribution that
includes a package manager such as MiKTeX or TeX Live/Mac TeX. For Windows
users, the MiKTeX package manager usually handles package installation
automagically during compilation of a document that is requesting a missing
package. The MiKTeX package manager, \code{mpm}, can also be run manually from
the command prompt:

\begin{tikzCodeNode}[title={Using \code{mpm} to install packages},listing style=bashsource,code body/.append style={codebody color=white}]
mpm --install packagename
\end{tikzCodeNode}

For versions of TeX Live and Mac TeX dated 2008 or newer, the \code{tlmgr}
package manager is used in an almost identical manner:

\begin{tikzCodeNode}[title={Using \code{tlmgr} to install packages},listing style=bashsource,code body/.append style={codebody color=white}]
tlmgr install packagename
\end{tikzCodeNode}

\subsection{Manual Installation}

Sometimes an automated package manager cannot be used. Common reasons may be
that one is not available, as is the case with the TeX Live 2007 distribution,
or that when running the package manager you do not have write access to the
location where \LaTeX\ packages are stored, as is the case with accounts on
shared computers. If this is the case, a manual install may be the best option
for making a \LaTeX\ package available.

Generally, the best place to find \LaTeX\ packages is the Comprehensive TeX
Archive Network, or \lang{CTAN} located at \url{http://www.ctan.org}. In the
case of the PGF/\TikZ\ package, the project homepage at
\url{http://www.sourceforge.net/projects/pgf} is also a good place to obtain
the package---especially if you would like to play with the bleeding-edge
development version.

Generally speaking, all \LaTeX\ packages are stored in a specially directory
called a \code{texmf} folder. Most \TeX\ distributions allow for each user to
have their own personal  \code{texmf} folder somewhere in their home path. The
most usual locations, and here {\bfseries\itshape usual} is an unfortunately
loose term, are as follows:

\begin{tikzCodeNode}[title={For UNIX/Linux},listing style=bashsource,code body/.append style={codebody color=white}]
~/texmf
\end{tikzCodeNode}

\begin{tikzCodeNode}[title={For Mac OS X},listing style=bashsource,code body/.append style={codebody color=white}]
~/Library/texmf
\end{tikzCodeNode}

\begin{tikzCodeNode}[title={For Windows, using MiKTeX},listing style=bashsource,code body/.append style={codebody color=white}]
# None predefined. However the following command will open
# the MiKTeX options panel and a new texmf folder may be assigned
# under the "Roots" tab.
mo
\end{tikzCodeNode}


The location of files and subfolders in the \code{texmf} directory should
follow a standard pattern called the \TeX\ Directory Structure or TDS which is
documented here: \url{http://tug.org/tds/tds.pdf}. Fortunately, most packages
available on \pkg{CTAN} are archived in such a way that they will unpack into
a TDS-compliant configuration. TDS-compliant archives usually have the phrase
\code{tds} somewhere in their filename and may be installed from a UNIX
shell\footnote{Sorry Windows users, we enjoy using command prompt about as much
as a poke in the eye with a sharp stick. Hence we don't use it enough to offer
advice. May we suggest \href{http://www.cygwin.com}{Cygwin}?} like so:

\begin{tikzCodeNode}[title={Installing \LaTeX{} package archives},listing style=bashsource,code body/.append style={codebody color=white}]
# For zip files.
unzip package.tds.zip -d /path/to/texmf

# For tarballs.
tar -xzf -C /path/to/texmf package.tar.gz
\end{tikzCodeNode}

For packages that aren't provided in TDS-compliant form look for installation
notes---usually provided in the form of an \code{INSTALL} file. If all else
fails \LaTeX\ packages can usually be installed by copying the files ending in
\code{.sty} to \code{texmf/tex/latex/}.

After package files have been unpacked to a \code{texmf} folder, the database
of installed packages needs to be updated for the \LaTeX\ compiler to take
notice of the additions. This is done with the \code{mktexlsr} command:

\begin{tikzCodeNode}[title={Registering new \LaTeX{} packages},listing style=bashsource,code body/.append style={codebody color=white}]
mktexlsr

# Successful package installation can be checked by running the
# kpsewhich command. For a package accessed in a document
# by \usepackage{package}, kpsewhich should return a path to
# package.sty
kpsewhich tikz.sty
!out/Users/Smithe/Library/texmf/tex/latex/pgf/frontendlayer/tikz.sty!/out
\end{tikzCodeNode}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Listing commands cannot be saved in macros, so we execute them here and stash
% the output in a box.
\newsavebox{\programflow}
\begin{lrbox}{\programflow}
\begin{tikzpicture}

  \node[text width = 4.3in] (r code) {
    \begin{tikzCodeNode}[title={\lang{R} User Types}, listing style=sweavechunk]
tikz('Rplot.tex')
plot(1)
dev.off()
    \end{tikzCodeNode}
  };

  \node[below = \baselineskip of r code, text width = 4.3in] (c code) {
    \begin{tikzCodeNode}[title={TikZ Device Translates}, listing style = csource]
static void TikZ_Circle( double x, double y, double r,
    const pGEcontext plotParams, pDevDesc deviceInfo){

...

  printOutput(tikzInfo,"\n\\path[");
  TikZ_WriteDrawOptions(plotParams, deviceInfo, ops);

  /* End options, print coordinates. */
  printOutput(tikzInfo, "] (%6.2f,%6.2f) circle (%6.2f);\n",
    x,y,r);
}
    \end{tikzCodeNode}
  };

  \node[below = \baselineskip of c code, text width = 4.3in] (latex code) {
    \begin{tikzCodeNode}[title={\LaTeX\ Output is Produced}, listing style = latexexample]
% Created by tikzDevice
% !TEX encoding = UTF-8 Unicode
\begin{tikzpicture}[x=1pt,y=1pt]

...

\path[draw=drawColor,line width= 0.4pt,
  line join=round,line cap=round]
  (264.94,258.95) circle (  2.25);

...

\end{tikzpicture}
    \end{tikzCodeNode}
  };

\end{tikzpicture}
\end{lrbox}


\partimage{
 \node[above left = 1in of current page.south east,
   anchor = south east,
   scale = 1.25
 ]
   % Here we use the box containing the output.
   {\usebox{\programflow}};
}

\part{Package Internals}
  \label{part:implementation}

\epigraph{We will encourage you to develop the three great virtues of a programmer: {\itshape laziness}, {\itshape impatience}, and {\itshape hubris}.}{{\itshape Programming Perl}\\ --{\scshape Larry Wall}}

\chapter{Introduction and Background}


We learn best through working with examples. When it comes to programming languages this involves taking working code that someone else has written, breaking it in as many places at it can possibly be broken, and then trying to build something out of the wreckage. Open source software facilitates this process wonderfully by ensuring the source code of a project is always available for inspection and experimentation. The \pkg{tikzDevice} its self was created by disassembling and then rebuilding Valerio Aimale's Pic\TeX{} device driver which is a part of the \lang{R} core codebase.

This section is our attempt to help anyone who may be experimenting with our code, and by extension the internals of the \lang{R} graphics system. There may also be useful, or useless, tidbits concerning building \lang{R} packages and interacting with the core \lang{R} language. The \lang{R} language can be extended in so many interesting and useful ways and it is our hope that the following documentation may provide a case study for anyone attempting such an extension.

We will make an attempt to assume no special expertise with any of the systems or programming languages leveraged by this package and described by this documentation. Therefore, if you are an experienced developer and find yourself thinking ``My god, are they {\bfseries really} about to launch into a description of how \lang{C} header files work?'', please feel free to skip ahead a few paragraphs. We received our formal introduction to computer programming in a college engineering program---therefore our programming background is rooted in Fortran (or, if you prefer, {\scshape fortran}). We are attempting to write the sort of documentation that we would have found invaluable at the start of this project

Therefore, this section is for all the budding developers like ourselves out there---people who have done some programming and who are starting to take a close look at the nuts and bolts of the \lang{R} programming environment. If you feel like you are wandering through a vast forest getting smacked in the face by every branch then maybe this section will help pull some of those branches out of the way...

...then again we have a lot of material to cover: \lang{R}, \lang{C}, \LaTeX , \TikZ{} , typography and the details of computerized font systems. Our grip may fail and send those branches flying back with increased velocity.

We wish you luck!\\
\vbox{}\quad{\itshape -The tikzDevice Team}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\chapter{Anatomy of an \lang{R} Graphics Device}

The core of an \lang{R} graphics device is a collection of functions, written in \lang{C}, that perform various specialized tasks. A description of some of these functions can be found in the {\itshape R Internals} manual while the main documentation is in the \lang{C} header file \code{GraphicsDevice.h}. For most \lang{R} installations this header file can be found in the directory \code{R\_HOME/include/R\_ext}. For copies of \lang{R} distributed in source code form, \code{GraphicsDevice.h} is located inside \code{R-version/src/include/R\_ext}. The following is a description of the functions each graphics device is expected to provide:


\setlength\columnsep{5em}

\begin{multicols}{2}


\section{Drawing Routines}

\begin{itemize}

\item[\code{circle}]{This function is required to draw a circle centered at a given location with a given radius.}

\item[\code{clip}]{This function specifies a rectangular area to be used a a clipping boundary for any device output that follows.}

\item[\code{line}]{This function draws a line between two points.}

\item[\code{polygon}]{This function draws lines between a list of points and then connects the first point to the last point.}

\item[\code{polyline}]{This function draws lines between a list of points.}

\item[\code{rect}]{This function is given a lower left corner and an upper right corner and draws a rectangle between the two.}

\item[\code{text}]{This function inserts text at a given location.}

\end{itemize}

\section{Font Metric Routines}

\begin{itemize}

\item[\code{metricInfo}]{This function is given the name of a single character and reports the ascent, descent and width of that character.}

\item[\code{strWidth}]{This function is given a text string and reports the width of that string.}

\end{itemize}

\section{Utility Routines}

\begin{itemize}

\item[\code{activate}]{This function is called when the device is designated as the active output device---i.e. by using \code{dev.set()} in \lang{R}}

\item[\code{close}]{This function is called when the device is shut down---i.e. by using \code{dev.off()} in \lang{R}}

\item[\code{deactivate}]{This function is called when another device is designated as the active output device.}

\item[\code{locator}]{This function is mainly used by devices with a GUI window and reports the location of a mouseclick.}

\item[\code{mode}]{This function is called when a device begins drawing output and again when the device finishes drawing output.}

\item[\code{newPage}]{This function initiates the creation of a new page of output.}

\item[\code{size}]{This function reports the size of the canvas the device is drawing on.}

\end{itemize}

\end{multicols}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{Calculating Font Metrics}

Font metrics are measurements associated with the glyphs, or printed characters, of a particular font. \lang{R} requires three of these metrics in order to produce correctly aligned output. The three metrics graphics devices are required to supply are:

\begin{tikzpicture}

\coordinate (centerpoint) at (0,0);

\node[anchor=north,outer sep=0pt] (title) at ($(centerpoint) + (4em,0)$) {\bfseries Ascent};

\node[scale=4,text=black!40,inner sep=0pt,outer sep=0pt,below=0.25em of title] (char) {g};
\draw[color=black,very thick] (char.base west) -- (char.base east);
\draw[color=black,very thick] (char.north west) -- (char.north east);
\draw[color=red,very thick,<->,>=stealth] ([xshift=10pt]char.base west) -- ([xshift=10pt]char.north west);


\newdimen\yone
\newdimen\ytwo

\pgfextracty{\yone}{\pgfpointanchor{char}{north}}
\pgfextracty{\ytwo}{\pgfpointanchor{char}{south}}
\pgfmathparse{ \yone - \ytwo }

\yone = \pgfmathresult pt

\node[anchor = north west,outer sep=0pt,text width=0.6\textwidth] at ($(centerpoint) + (8em, 0)$){
Ascent is the distance between the baseline and the tallest point on a
character's glyph. For the ``g'' printed to the left, the ascent has been
calculated as: \the\yone
};
\end{tikzpicture}



\begin{tikzpicture}

\coordinate (centerpoint) at (0,0) {};

\node[anchor=north,outer sep=0pt] (title) at ($(centerpoint) + (4em,0)$) {\bfseries Descent};

\node[scale=4,text=black!40,inner sep=0pt,outer sep=0pt,below= 0.25em of title.south] (char) {g};
\draw[color=black,very thick] (char.base west) -- (char.base east);
\draw[color=black,very thick] (char.south west) -- (char.south east);
\draw[color=red,very thick,<-,>=stealth] ([xshift=10pt]char.south west) -- +(0,-6pt);
\draw[color=red,very thick,<-,>=stealth] ([xshift=10pt]char.base west) -- +(0,+6pt);


\newdimen\yone
\newdimen\ytwo

\pgfextracty{\yone}{\pgfpointanchor{char}{base}}
\pgfextracty{\ytwo}{\pgfpointanchor{char}{south}}
\pgfmathparse{ \yone - \ytwo }

\yone = \pgfmathresult pt

\node[anchor = north west,outer sep=0pt,text width=0.6\textwidth] at ($(centerpoint) + (8em, 0)$){
Descent is the distance between the baseline and the lowest point on a
character's glyph. For the ``g'' printed to the left, the descent has been
calculated as: \the\yone
};
\end{tikzpicture}



\begin{tikzpicture}

\coordinate (centerpoint) at (0,0);

\node[outer sep=0pt,anchor=north] (title) at ($(centerpoint) + (4em,0)$) {\bfseries Width};

\node[scale=4,text=black!40,inner sep=0pt,outer sep=0pt,below= 0.25em of title.south] (char) {g};
\draw[color=black,very thick] (char.south west) -- (char.north west);
\draw[color=black,very thick] (char.south east) -- (char.north east);
\draw[color=red,very thick,<->,>=stealth] (char.base west) -- (char.base east);

\newdimen\xone
\newdimen\xtwo

\pgfextractx{\xone}{\pgfpointanchor{char}{east}}
\pgfextractx{\xtwo}{\pgfpointanchor{char}{west}}
\pgfmathparse{ \xone - \xtwo }

\xone = \pgfmathresult pt

\node[anchor = north west,outer sep=0pt,text width=0.6\textwidth] at ($(centerpoint) + (8em, 0)$){
Width is the distance between the left and right sides of a character's glyph.
For the ``g'' printed to the left, the width has been calculated as: \the\xone};
\end{tikzpicture}

Providing font metrics and string widths is without a doubt the most difficult task a \lang{R} graphics device must undertake. The calculation of string widths is made even more difficult for the \pkg{tikzDevice} as we attempt to process arbitrary \LaTeX{} strings. Inside \lang{R} the string ``\verb`$\alpha$`'' literally has 8 characters, but when it is typeset it only has one: $\alpha$.

Calculating font metrics is a tricky business to begin with and the fact that the typeset representation of a \LaTeX{} string is different from its representation in source code compounds the difficulty of the task immensely. Therefore, we took the path of laziness and started looking for an easy way out (remember the three great virtues of a programmer?). The solution we came up with seemed easy enough---make \LaTeX{} calculate these metrics for us, after all that is what a \LaTeX{} compiler does for a living.

Now, how to do that?

\subsection{Character Metrics}

As a starting point, let's examine the interface of the \lang{C} function that \lang{R} calls in order to determine character metrics:

\begin{tikzCodeBlock}[title={Function declaration for \code{metricInfo}}]
void (metricInfo)(int c, const pGEcontext gc,
  double* ascent, double* descent, double* width,
  pDevDesc dd);
\end{tikzCodeBlock}

The most important variables involved in the function are \code{c}, \code{ascent}, \code{descent} and \code{width}. The incoming variable is \code{c}, which contains the character for which \lang{R} is requesting font metrics. Interestingly, \code{c} is passed as an integer, not a character as one might expect. What's up with that? Well, the short answer is that \lang{R} passes the \code{ASCII} or \code{UTF8} {\itshape symbol code} of a character and not the character itself. How to use that character code to recover a character will be explained later.

The outgoing variables are \code{ascent}, \code{descent} and \code{width}. The asterisks, `*', in their definitions mean these variables are passed as {\itshape pointers} as opposed to {\itshape values}. A complete discussion of the differences between pointers and values could, and has, filled up several chapters of several programming books. The important distinction in context of the \code{metricInfo} function is that when a number is assigned to a pointer variable, that number is available elsewhere after the function terminates. In contrast, when a number is assigned to a value variable, that number disappears when the function ends unless it is explicitly sent back out to the wide world through the \code{return} statement. So, the main task of the \code{metricInfo} function is to assign values to \code{ascent}, \code{descent} and \code{width}.

The other two variables present in the function are the \code{pGEcontext} variable \code{gc} and the \code{pDevDesc} variable \code{dd}. \code{gc} contains information such as the font face, foreground color, background color, character expansion factor, ect. currently in use by the graphics system. \code{dd} is the object which contains \lang{R}'s representation of the graphics device. For the sake of simplifying the following discussion, we will ignore these variables.

So, to recap---we have an integer \code{c} coming in that represents a code for a character in the \code{ASCII} or \code{UTF8} symbol tables (for the sake of the following discussion, we will assume \code{ASCII} characters only). Our overall task is to somehow turn that integer into three numbers which can be assigned to the pointer variables \code{ascent}, \code{descent} and \code{width}. And, since we're being lazy, we've decided that the best way to do that is to ask the \LaTeX{} compiler to compute the numbers for us.

Recovering these numbers from the \LaTeX{} compiler involves the execution of three additional tasks:

\begin{enumerate}

  \item{We must write a \LaTeX{} input file that contains instructions for calculating the metrics.}

  \item{We call the \LaTeX{} compiler to process that input file.}

  \item{We must read the compiler's output in order to recover the metrics.}

\end{enumerate}

Each of these tasks could be executed from inside our \lang{C} function, \code{metricInfo}. However, we will run into some difficulties---namely with step 2, which involves calling out to the operating system with orders to run \LaTeX . Each operating system handles these calls a little differently and our package must attempt to get this job done whether it is running on Windows, UNIX, Linux or Mac OS X.

Portable \lang{C} code could be written to handle each of these situations, but that is starting to sound like work and we're trying to be lazy here. What we need is to be able to work at a higher {\itshape level of abstraction}. That is---instead of using \lang{C}, we need to be working inside a language that shields us from such details as what operating system is being used. \lang{R} may have called this \lang{C} function to calculate font metrics, but we really want to do the actual computations back inside \lang{R}.

\subsection{Calling \lang{R} Functions from \lang{C} Functions}

The ``Ritual of the Calling of the \lang{R} Function'' is easy enough to perform as long as you don't have burning need to know all the details of the objects you are handling. The \lang{C} level representation of a \lang{R} object such as a variable or function is an object known as a \code{SEXP}. For the exact details on what a \code{SEXP} is and how it works, we refer the interested user to chapter one of the {\itshape \lang{R} Internals} manual.

The \lang{R} function we will be calling is declared in the \lang{R} environment as follows:

\begin{tikzCodeBlock}[title={Definition of target \lang{R} function},listing style=sweavechunk]
getLatexCharMetrics <- function( charCode ){

  # System call to LaTeX

}
\end{tikzCodeBlock}

In order to call this function for \lang{C}, we need a vector composed of two \lang{C}-level \lang{R} objects---one containing the name of the function we are calling and another one containing the value we are passing for \code{charCode}. This is set up in \lang{C} as follows:

\begin{tikzCodeBlock}[title={Preparing a \lang{R} function call inside \lang{C}}]
void (metricInfo)(int c, const pGEcontext gc, double* ascent, double* descent,
  double* width, pDevDesc dd){

  SEXP RCallBack;
  PROTECT( RCallBack = allocVector(LANGSXP, 2) );

  SEXP metricFun = findFun( install("getLatexCharMetrics"), R_Global_Env );

  SETCAR( RCallBack, metricFun );

  SETCADR( RCallBack, ScalarInteger( c ) );
  SET_TAG( CDR( RCallBack ), install("charCode") );

  \\ To be continued...

}
\end{tikzCodeBlock}

The first thing that happens in the code chunk above is that a new \code{SEXP} variable named \code{RCallBack} is created. This variable will be the agent through which we will communicate with the \lang{R} environment. The next action is to allocate our callback variable as a vector of length 2-- we need one slot for the \lang{R} function name and one slot for the value that is being passed into the function. This allocation happens inside the \lang{R} environment, so it is executed inside the \code{PROTECT} statement. The reason for using \code{PROTECT} is that the \lang{R} garbage collector is constantly on the prowl for unused objects in the \lang{R} environment. An object is considered ``unused'' if it is not attached to any variable name in the \lang{R} environment. Since the object is only attached to the variable \code{RCallBack} in our \lang{C} function, the \lang{R} garbage collector will see it a valid candidate for deletion. The purpose of \code{PROTECT} is to keep our new vector from being trashed.

The next portion of the \lang{C} function retrieves the \lang{R} function object for \code{getLatexCharMetrics}. The function is searched for in \lang{R} global namespace, so it must be one that is available to the user from the \lang{R} command prompt when the package is loaded. The function is stored in the \code{SEXP} variable \code{metricFun}. We do not have to involve \code{PROTECT} in the assignment since \code{getLatexCharMetrics} exists as a variable name in the \lang{R} environment.

The last portion of the code chunk is responsible for loading the function name and call value into \code{RCallBack}. The \code{CAR} statement is used to retrieve the value of a \code{SEXP} variable and the \code{SETCAR} statement is used to set the value of a \code{SEXP}. In this case we use \code{SETCAR} to designate the \lang{R} function stored in \code{metricFun} as the first value of \code{RCallBack}.

When dealing with a vector \code{SEXP} such as \code{RCallBack}, which has 2 slots, we need to use a different function to access the second slot. The \code{CDR} function will allow us to move to the second slot in \code{RCallBack} where we may perform a \code{SETCAR} to specify a value. In the example code, these operations were combined by using the \code{SETCADR} function which has the same effect as:

\begin{tikzCodeBlock}[listing style=sweavechunk]
SETCAR( CDR(RCallBack), ScalarInteger( c ) );
\end{tikzCodeBlock}

After assigning the value of the \lang{C} variable \code{c} as the second value of \code{RCallBack}, we need to ``tag'' it as the value that corresponds to the \code{charCode} argument of \code{getLatexCharMetrics}. This is done by using the \code{SET\_TAG} function. Once again, we use \code{CDR} to shift our area of operation to the second slot of \code{RCallBack}. Now that the \code{RCallBack} object is set up, we are ready to actually call the \code{getLatexCharMetrics} function.

\begin{tikzCodeBlock}[title={Executing a \lang{R} function call inside \lang{C}}]
SEXP LatexMetrics;
PROTECT( LatexMetrics = eval( RCallBack, R_GlobalEnv) );
\end{tikzCodeBlock}

And that's it! We create a new \code{SEXP} to hold the return values of \code{getLatexCharMetrics} and execute the \code{eval} function to cause \code{getLatexCharMetrics} to be executed inside the \lang{R} environment. The details of the \lang{R} function will be explained in the next section, for now let's assume that it returns the three values we're interested in as a vector of three numbers. How do we extract these values and assign then to \code{ascent}, \code{descent} and \code{width}?

\begin{tikzCodeBlock}[title={Recovering return values from a \lang{R} function call}]
  *ascent = REAL(RMetrics)[0];
  *descent = REAL(RMetrics)[1];
  *width = REAL(RMetrics)[2];

  UNPROTECT(2);

  return;
\end{tikzCodeBlock}

Here the \code{REAL} function is used to coerce the \code{SEXP} variable \code{RMetrics} to a vector of real numbers. These numbers are then extracted and assigned to the return values of \code{metricInfo}. In \lang{C} we must specify the `first' value in a vector using the index 0 rather than the index 1. \footnote{There are good logical reasons for this from the point of view of a computer scientist---but if your background in arrays is rooted in linear algebra it will be a bit disorienting.} The last thing to do is release the restrictions we placed on the \lang{R} garbage collector. Since we used the \code{PROTECT} function twice, we must call \code{UNPROTECT} and pass 2 as the argument.

\subsection{Implementing a System Call to \LaTeX}

Now we may turn to the actual guts of the \lang{R} function \code{getLatexCharMetrics}.  The first thing we need to do is set up a file for \LaTeX{} input:

\begin{tikzCodeBlock}[title={Creating a \LaTeX{} input file},listing style=sweavechunk]
getLatexCharMetrics <- function( charCode ){

  texDir <- tempdir()

  texLog <- file.path( texDir,'tikzStringWidthCalc.log' )
  texFile <- file.path( texDir,'tikzStringWidthCalc.tex' )

  texIn <- file( texFile, 'w')

  # To be continued...
\end{tikzCodeBlock}

The first thing we do is choose a place to create this input file. Now, when the \LaTeX{} compiler is run on a \code{.tex} file, a lot of additional files get created---the whole process is a bit messy. Since the user probably wouldn't appreciate having to clean up our mess, we use the \code{tempdir()} function to retrieve a path to a {\itshape temporary directory} on the system. Here is the first place we benefit from the added level of abstraction granted by \lang{R}. Each operating system has different locations for temporary directories. If we were still working in \lang{C}, we would have to worry about such details. \lang{R} takes care of those details for us.

Now that we have a place to work, we set up a couple of filenames---one for the input file, which ends in \code{.tex} and one for the \LaTeX{} log file, which ends in \code{.log}. We then open the \code{.tex} file for writing. The next step is to setup the preamble of the \LaTeX{} file.

\begin{tikzCodeBlock}[title={Setting up the preamble of a \LaTeX{} input file},listing style=sweavechunk]
  writeLines("\\documentclass{article}", texIn)

  writeLines("\\usepackage[T1]{fontenc}", texIn)

  writeLines("\\usepackage{tikz}", texIn)
  writeLines("\\usetikzlibrary{calc}", texIn)

  writeLines("\\batchmode", texIn)
\end{tikzCodeBlock}

Here we have started a standard \LaTeX{} input file by specifying
\code{article} as the document class. We also add the \code{fontenc} package
and specify \code{T1} as its option. This ensures we are using the Type 1 font
encoding---by default \TeX{} and \LaTeX{} use an encoding called \code{OT1}. Why
do we need to worry about font encodings? Well, a font encoding specifies which
\code{ASCII} symbol codes map to which characters and by default, \lang{R}
expects us to be using the Type 1 encoding (\lang{R} does support other
encodings---but we're ignoring that for now). For example, in the Type 1
encoding, the character that corresponds to the \code{ASCII} code 60 is the
less-than sign: `{\char60}'. If we were to allow \TeX{}
to retain its default \code{OT1} encoding, that same character code would
instead map to an upside-down exclamation point: `{\usefont{OT1}{lmr}{m}{n}\char60}'.

The other two packages we load are the \code{tikz} package and its \code{calc}
library. Essentially we will have \TikZ{} drop the character into a box and
report some measurements concerning the size of that box. The last command,
\code{batchmode} tells \LaTeX{} that there isn't any user available to interact
with---so it should not bother to stop and ask any questions while processing this
file.

The next step is to set up the part of the \LaTeX{} file that will actually
calculate and report the widths we are looking for. As mentioned before, this
is done by setting the character inside a \TikZ{} node and extracting the
dimensions of the box that surrounds it. In an attempt to improve clarity, the
following code will be presented as straight \LaTeX{} --
\code{getLatexCharMetrics} inserts it into the \code{texIn} file by means of
\code{writeLines} as we have been doing all along. The string highlighted in
{\color{red} red} should be replaced with the value of the variable charCode
that was passed in to the function \code{getLatexCharMetrics}.

\begin{tikzCodeBlock}[title={Extracting character dimensions using \TikZ},listing style=latexexample]
\begin{tikzpicture}

\node[inner sep=0pt,outer sep=0pt] (char) {\charXXcharCodeXX};

\path let \p1 = ($(char.east) - (char.west)$),
  \n1 = {veclen(\x1,\y1)} in (char.east) -- (char.west)
  node{ \typeout{tikzTeXWidth=\n1} };

\path let \p1 = ($(char.north) - (char.base)$),
  \n1 = {veclen(\x1,\y1)} in (char.north) -- (char.base)
  node{ \typeout{tikzTeXAscent=\n1} };

\path let \p1 = ($(char.base) - (char.south)$),
  \n1 = {veclen(\x1,\y1)} in (char.base) -- (char.south)
  node{ \typeout{tikzTeXDescent=\n1} };
\end{tikzCodeBlock}

What the heck just happened? Well, first we instructed \LaTeX{} to enter the \TikZ{} picture environment using \verb`\begin{tikzpicture}`. Then we ordered \TikZ{} to create a node named ``char'' containing the command \verb`\char` followed by the value of charCode. For example, if we were passed `103' as the character code, which corresponds to the character `g', the node line should be:

\begin{tikzCodeBlock}[listing style=latexexample]
\node[inner sep=0pt,outer sep=0pt] (char) {\char103};
\end{tikzCodeBlock}

The \code{inner sep} and \code{outer sep} options are set to \code{0pt} in order to ensure the boundaries of the node `hug' the contents tightly. Now the whole point of setting the character inside a node is that \TikZ{} defines `anchors' along the bounding box of the node. All anchors are referred using a \code{node name.posistion} notation. Since we named the node \code{char}, all the anchors start with \code{char}. The anchor posistions relevant to our problem are shown below:

\begin{center}
\begin{tikzpicture}

  \node[draw=black, very thick,inner sep=0, outer sep=0, text=black!40,scale=14]
    (char) {\char103};

  \foreach \anchor/\placement in
    {north/above, south/below, base/below, east/right, west/left} {

    \draw[shift=(char.\anchor),color=red] plot[mark=*] coordinates{(0,0)}
      node[\placement,text=red] {\small\texttt{(char.\anchor)}};
  }

  \node[above= 1em of char.north] {Node Bounding Box}
    edge[ultra thick,->,>=stealth,out=0,in=0] ($(char.10) + (6pt,12pt)$);


\end{tikzpicture}
\end{center}

The `base' anchor sits on the baseline of the text---therefore to calculate the ascent of the character `g', all we have to do is figure out the difference in height between the positions \code{char.north} and \code{char.base}. Similarly, for the descent we would calculate the difference in height between \code{char.base} and \code{char.south} and width can be obtained using \code{char.west} and \code{char.east}. This is the purpose of the admittedly cryptic \verb`\path` commands that are inserted in the \LaTeX{} input file. Let's examine one of them:

\begin{tikzCodeBlock}[]
\path let \p1 = ($(char.north) - (char.base)$),
  \n1 = {veclen(\x1,\y1)} in node{ \typeout{tikzTeXAscent=\n1} };
\end{tikzCodeBlock}

So, what exactly is going on here? Normally, the \verb`\path` command is used to draw lines between points and add additional coordinates or nodes along those lines. For example, the command:

\begin{tikzCodeBlock}[]
\path[draw] (0,0) -- (1,1) node {Hi!};
\end{tikzCodeBlock}

Draws a line from \code{(0,0)} to \code{(1,1)} and places a node at \code{(1,1)} containing the word `Hi!'. In the \TikZ{} code produced by \code{getLatexCharMetrics}, the \code{let} operation is specified. Basically, \code{let} postpones the actual drawing of a path and performs calculations until the \code{in} keyword is encountered. The result of these calculations are stored in a set of special variables which must start with \verb`\n`, \verb`\p`, \verb`\x` or \verb`\y`. The first \code{let} operation executed is:

\begin{tikzCodeBlock}[]
\p1 = ( $(char.north) - (char.base)$ )
\end{tikzCodeBlock}

This performs a vector subtraction between the coordinates of \code{char.north} and \code{char.base}. The resulting x and y components are stored in the `point' variable \verb`\p1`. The second operation executed is:

\begin{tikzCodeBlock}[]
\n1 = {veclen(\x1,\y1)}
\end{tikzCodeBlock}

This \code{let} operation treats the coordinates stored in \verb`\p1` as a vector and calculates its magnitude. The `1' appended to the \verb`\x` and \verb`\y` variables specifies that we are accessing the x and y components of \verb`\p1`. This result is stored in the `number' variable \verb`\n1`. Now, that our metric is stored in \verb`\n1`, our final task is to ensure it makes it into the \LaTeX{} \code{.log} file---this is done by adding a \code{node} containing the \verb`\typeout` command. The contents of the node:
\begin{tikzCodeBlock}[]
\typeout{tikzTexAscent=\n1}
\end{tikzCodeBlock}
cause the phrase `tikzTexAscent=' to appear in the \code{.log} file---followed by the ascent calculated using the node anchors. After the ascent, descent and width have been calculated the \LaTeX{} compiler may be shut down, this is done by adding the final two lines to the input file:

\begin{tikzCodeBlock}[title={Terminating a \LaTeX{} compilation},listing style=sweavechunk]
  writeLines("\\makeatother", texIn)

  writeLines("\\@@end", texIn)

  close(texIn)
\end{tikzCodeBlock}

Now that the input file has been prepped, we must process it using the \LaTeX{} compiler and load the contents of the resulting \code{.log} so that we may search for the metrics we dumped using \verb`\typeout`.

\begin{tikzCodeBlock}[title={Terminating a \LaTeX{} compilation},listing style=sweavechunk]
  latexCmd <- getOption('tikzLatex')
  latexCmd <- paste( latexCmd, '-interaction=batchmode',
    '-output-directory', texDir, texFile)

  silence <- system( latexCmd, intern=T, ignore.stderr=T)

  texOut <- file( texLog, 'r' )

  logContents <- readLines( texOut )
  close( texOut )
\end{tikzCodeBlock}

The \LaTeX{} compiler is executed through the \code{system} function which handles the details of implementing a system call on whatever operating system we happen to be using. We assign the return value of the \code{system} function to a dummy variable called \code{silence} so that no output floods the user's screen. The last task is to extract our metrics from the text of the \code{.log} we loaded.

\begin{tikzCodeBlock}[title={Parsing the \code{.log} file text},listing style=sweavechunk]
  match <- logContents[ grep('tikzTeXWidth=', logContents) ]
  width <- gsub('[=A-Za-z]','',match)

  match <- logContents[ grep('tikzTeXAscent=', logContents) ]
  ascent <- gsub('[=A-Za-z]','',match)

  match <- logContents[ grep('tikzTeXDescent=', logContents) ]
  descent <- gsub('[=A-Za-z]','',match)

  return( as.double( c(ascent,descent,width) ) )
\end{tikzCodeBlock}

Here we use the \code{grep} function to search through the log output for the tags `tikzTeXWidth=', `tikzTeXAscent=' and `tikzTeXDescent=' that we specified when we used \verb`\typeout`. After we recover a line containing one of these tags, we use the \code{gsub} command to remove the letters and the equals sign from the text line---leaving just the number we're interested in. These values are then coerced using \code{as.double} and set as the return value of \code{getLatexCharMetrics}.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\chapter{On the Importance of Font and Style Consistency in Reports}
If you haven't figured it out by now, we are quite picky about the way our graphics and reports look.  We are especially picky about the consistency in fonts (both sizes and shapes).  Without launching into a diatribe about this, we just want to say with tools like \pkg{tikzDevice} you no longer have to settle for what is ``just okay.'' So go nuts, be picky about how your text and graphics look.  Don't be afraid to snub your nose at reports which pay no attention to detail.  Be that person who says ``NO! I wont settle for half rate graphics, I want the best!''

\section{The \pkg{pgfSweave} Package and Automatic Report Generation}
Now for a little shameless self promotion. The authors of \pkg{tikzDevice} have another package called \pkg{pgfSweave} which provides a driver for Sweave.  \pkg{pgfSweave} started as an interface to \href{http://sourceforge.net/projects/eps2pgf/}{eps2pgf} and its ability to interpret strings in eps files as \LaTeX{}.  This was used to much the same effect as \pkg{tikzDevice}.  The problem was the conversion from eps to pgf was SLOW.  Long story short, by combining this functionality with the externalization feature of pgf and the \pkg{cacheSweave} we were able to achieve bearable compilation speed and nice looking graphics.   \pkg{pgfSweave} is in the process of getting pumped up by interfacing with the \pkg{tikzDevice} package.   We hope that the combination will be a self-caching, consistency-inducing, user-empowering tool for high quality reports.

\newpage

\bibliography{refs}

\end{document}
