# formatting certain texts in \fancyvrb environments automatically

I have for example the following Verbatim environment from the fancyvrb package:

\begin{Verbatim}
>>> 1+1
2
>>>
\end{Verbatim}


Whenever ">>>" appears, I want to color it blue. Instead of manually coloring those, can I do the coloring job automatically?

The right tool for your use case is the listings package: In addition to coloring the prompts, it will do a whole bunch of other things appropriate to code as well. It doesn't color python prompts by default, but it's easy to customize.

It can be as simple as this:

\usepackage{listings}
\usepackage{xcolor}
\lstset{
otherkeywords={>>>},     % used only because >>> is not an identifier
morekeywords=[3]{>>>},
keywordstyle={[3]\color{blue}}
}

\begin{document}
\begin{lstlisting}
>>> 1+1
2
>>>
\end{lstlisting}


But you'll probably want a few more adjustments to make it more python-like. If you like syntax coloring, add style={python-idle-code} to \lstset{} to get an IDLE-like color scheme. (It's defined in listings-python.prf, which must be included separately. Clunky...) Or you could use language={python}, for a black and white basic scheme. Either way, I would also recommend showstringspaces=false and tabsize=4. So here's a complete almost-MWE:

\documentclass{article}

\usepackage{listings}
\usepackage{xcolor}

% Optional:
\input{listings-python.prf}
\lstset{
style={python-idle-code},
showstringspaces=false,  % true by default for python
% tabsize=4,
}

% Blue prompts
\lstset{
otherkeywords={>>>},    % used only because >>> is not an identifier
morekeywords=[3]{>>>},
keywordstyle={[3]\color{blue}},
}

\begin{document}
\begin{lstlisting}
>>> 1+1
2
>>> def hello():
print("Hello, world!")
\end{lstlisting}

\end{document}


Output:

Here an approach, just insert your verbatim text inside VerbatimOut environment

\documentclass{article}
\usepackage{fancyvrb}
\usepackage{xcolor}

\begin{document}

\begin{VerbatimOut}{file.txt}
>>> 1+1
2
>>>
\end{VerbatimOut}

{
\def\greater{\char62}
\catcode>=\active
\VerbatimInput[defineactive={\def>{\textcolor{blue}{\greater}}}]{file.txt}
}

\end{document}


Result

• Answer updated. – Salim Bou Oct 3 '15 at 1:06
• This also colours single > signs, which does not seem to be what the OP is asking for. – Andrew Swann Oct 7 '15 at 7:12
• Replace \def> with \def>>>. – Salim Bou Oct 7 '15 at 11:41
• and if the code contains >>>> ? – Andrew Swann Oct 7 '15 at 13:21
• Also \def>>> does not work, single > results in  Use of > doesn't match its definition`. – Andrew Swann Oct 7 '15 at 13:23