[Tex/LaTex] How to ensure all teletype/monospaced text is in a certain color

colortypewriter

I'm trying to include some monospaced text, and I'd like it to be in a different color than the normal text. There will be several (read: hundreds) of instances of monospaced text, and I want it all to be in a certain color. I'm relatively new to LaTeX (only started using it in the last 8 months or so), so I can't offer much in the way of research.

I've imported the color package, so far. I'm looking for all instances of \texttt and \verb to be in a certain color, without having to type \color in front of all of them.

Best Answer

You could redefine \texttt to take an optional argument that allows you to switch colour if necessary, and if not, stick to some default colour.

In the minimal example below, \texttt[<color>]{<stuff>} has been redefined to take an optional <color> (default is black).

enter image description here

\documentclass{article}
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\let\oldtexttt\texttt% Store \texttt
\renewcommand{\texttt}[2][black]{\textcolor{#1}{\ttfamily #2}}% \texttt[<color>]{<stuff>}
\begin{document}
Here is some \texttt{monospaced} text that has 
\texttt[blue]{a different colour}. You can even use 
\texttt[green!30!red]{colour mixtures}.
\end{document}

The use of xcolor allows you to mix/blend colours as well rather than sticking to some fixed colour model.

The command \let\oldtexttt\texttt "stores" \texttt in \oldtexttt if you want to use it for something else. It's wasn't necessary for my example, but may have an impact in your larger document.

Related Question