Alternately coloured line environment with fancyvrb

[This article was first published on The Praise of Insects, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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}

To leave a comment for the author, please follow the link and comment on their blog: The Praise of Insects.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)