# Randomly color paragraphs in LaTeX document

I usually type up my notes for school in LaTeX, and I find it easier to focus on text where the color changes between paragraphs, which is easy to do with old fashioned pen and paper.

On LaTeX, however, is there a way where the compiler can automatically do this while rendering my pdf changing the color of random paragraphs?

-

## 2 Answers

Solution Idea

At the start of each paragraph, generate three random numbers between 0 and 255, use them as RGB parameters to generate a color, apply the color at the start of paragraph.

The Code

\documentclass{article}

\usepackage{insdljs}
\usepackage{rangen}

\usepackage{xcolor}

\usepackage{lipsum}

\def\randomlycolorparagraph{%
% Get random color paramaters
\RandomZ{\R}{0}{255}%\R
\RandomZ{\G}{0}{255}%\G
\RandomZ{\B}{0}{255}%\B
% Generate random color
\definecolor{randomcolor}{RGB}{\R,\G,\B}
% Use color
\color{randomcolor}}

\def\randomlycoloreveryparagraph{\everypar={\randomlycolorparagraph}}

\AtBeginDocument{\randomlycoloreveryparagraph}

\begin{document}

\lipsum[1-40]

\end{document}


Solution Details

This solution uses the rangen package, specifically the \RandomZ command to generate three random numbers between 0 and 255. These three numbers are then used as RGB values in the \definecolor command from xcolor package.

All the above are bundled in a macro which is applied at the start of a paragraph using the \everypar command.

I went one step further and hooked the \everypar with \AtBeginDocument. So, the random color effect starts at the start of a document. Should you want the random effect start at some mid point, please put the \randomlycoloreveryparagraph command where you want the random effect to start.

The Output

Your output is likely to look different. The colors are supposed to be random.

Tips

Should you want the RGB values in a certain range, tweak the range values in the \RandomZ commands.

-
Good idea. But I don't have insdljs with my TeXlive 2013 full installed. According to CTAN Con­tained in MiKTeX as acro­tex it is only for MikTeX? –  Sigur Feb 1 at 16:59
@Sigur This is not at all for MikTeX only. I also had to install it fresh in my Ubuntu machine. And I am always a command line guy. –  Masroor Feb 1 at 17:05

You need no external package (except for xcolor) if you use pdfTeX or LuaTeX (not XeTeX) as engine.

\documentclass{article}
\usepackage{everyhook,xcolor}

\newcommand{\randomcolor}{%
\definecolor{randomcolor}{RGB}
{
\pdfuniformdeviate 256,
\pdfuniformdeviate 256,
\pdfuniformdeviate 256
}%
\color{randomcolor}%
}

\PushPostHook{par}{\randomcolor}

\begin{document}

\section{First}

One

Two

Three

\section{Second}

Four

Five

Six

\end{document}


The primitive \pdfuniformdeviate must be followed by an integer and expands to a uniformly distributed random integer between 0 (included) and the given number (excluded).

Using everyhook is safer than playing directly with \everypar.

-