Sunday, 11 September 2011

Alternately coloured line environment with fancyvrb

Recently, while typing up an R tutorial, I used the LaTeX fancyvrb package to create two environments—one coloured blue for R commands, and one coloured red to display R output. This worked well for large blocks of each type. Then I decided I wanted to display a number of one-line commands and output alternately. Looking up the fancyvrb package documentation, it was easy to get alternate colours. The problem was, it did it globally. My environments for input and output also went psychedelic.

After a bit of messing around, I discovered the following solution. My red environments remain red, my blue environments stay blue, and alternate colours only turn up when I want them to!


\documentclass{article}
\usepackage{fancyvrb}
\usepackage{color}

\newcommand{\ChangeLine}[1]{%
\ifodd\value{FancyVerbLine}%
\textcolor{blue}{#1}\else\textcolor{red}{#1}\fi}

\DefineVerbatimEnvironment{blueEnv}{Verbatim}{formatcom=\color{blue}}{}
\DefineVerbatimEnvironment{redEnv}{Verbatim}{formatcom=\color{red}}{}
\DefineVerbatimEnvironment{alternate}{Verbatim}{formatcom=\renewcommand{\FancyVerbFormatLine}{\ChangeLine}}{}


\begin{document}

\begin{Verbatim}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{Verbatim}

\begin{blueEnv}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{blueEnv}

\begin{redEnv}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{redEnv}

\begin{alternate}
aaaaaaaaaaa
bbbbbbbbbb
cccccccccccc
ddddddddddddd
\end{alternate}

\end{document}

No comments: