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}

enter image description here

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}

enter image description here


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}

enter image description here

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}

enter image description here


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 pack­age de­fines the alltt en­vi­ron­ment which is like the ver­ba­tim en­vi­ron­ment ex­cept that \ and braces have their usual mean­ings. Thus, other com­mands and en­vi­ron­ments can ap­pear within an alltt en­vi­ron­ment.

enter image description here

\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}

Tags:

Verbatim

Color