6

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?

Chang
  • 9,528

2 Answers2

4

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

enter image description here

Salim Bou
  • 17,021
  • 2
  • 31
  • 76
4

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:

colored python

alexis
  • 7,961