Use color in verbatim environment
Not exactly the same solution pointed by flav:
\documentclass[]{article}
\usepackage{fancyvrb}
\usepackage{xcolor}
\begin{document}
\begin{Verbatim}[commandchars=\\\{\}]
a (black)
\textcolor{red}{b} (I want this letter to be red)
\end{Verbatim}
\end{document}
Note: Credits to fancyvrb
documentation
Answer to follow-up
question:
To change the color for all contents of verbatim
use a colored scope.
\documentclass[]{article}
\usepackage{fancyvrb}
\usepackage{xcolor}
\begin{document}
\begin{Verbatim}[commandchars=\\\{\}]
a (black)
\textcolor{red}{b} (I want this letter to be red)
\end{Verbatim}
{
\color{blue}
\begin{Verbatim}[commandchars=\\\{\}]
a (black)
\textcolor{red}{b} (I want this letter to be red)
\end{Verbatim}
}
\end{document}
A verbatimbox
approach, using <
and >
as active delimiters of the red text. Invoked by providing the \vbdelim
macro as the optional argument to the verbnobox
environment.
\documentclass{article}
\usepackage{xcolor,verbatimbox}
\catcode`>=\active %
\catcode`<=\active %
\def\openesc{\color{red}}
\def\closeesc{\color{black}}
\def\vbdelim{\catcode`<=\active\catcode`>=\active%
\def<{\openesc}
\def>{\closeesc}}
\catcode`>=12 %
\catcode`<=12 %
\begin{document}
\begin{verbnobox}[\vbdelim]
a (black)
<b> (I want this letter to be <red>)
\end{verbnobox}
\end{document}
Here is a more general version in which the color can be provided as an optional argument to <
\documentclass{article}
\usepackage{xcolor,verbatimbox}
\catcode`>=\active %
\catcode`<=\active %
\newcommand\openesc[1][red]{\color{#1}}
\def\closeesc{\color{black}}
\def\vbdelim{\catcode`<=\active\catcode`>=\active%
\def<{\openesc}
\def>{\closeesc}}
\catcode`>=12 %
\catcode`<=12 %
\begin{document}
\begin{verbnobox}[\vbdelim]
a (black)
<b> (I want this letter to be <red>)
<[blue!45]c> and this one to be <[blue!45]blue!45>
\end{verbnobox}
\end{document}
If your verbatim
environment doesn't really contain stuff that requires it (that is, it's just regular text), consider using the alltt
environment (from alltt
):
The
alltt
package defines thealltt
environment which is like theverbatim
environment except that\
and braces have their usual meanings. Thus, other commands and environments can appear within analltt
environment.
\documentclass{article}
\usepackage{alltt,xcolor}
\begin{document}
\begin{alltt}
a (black)
\textcolor{red}{b} (I want this letter to be red)
\end{alltt}
\end{document}