# How to preprocess code inside a listings (or fancyvrb) environment?

Suppose I want to make a shell environment to typeset examples of shell commands. I'd like to automate some details to remain consistent. For example, I need to automatically put a '$' at the beginning of the first line, so a piece of code like: \begin{shell} cat nothing > /dev/null cat: nothing: No such file or directory \end{shell}  would be typeset as if the code were written as: $ cat nothing > /dev/null
cat: nothing: No such file or directory


This idea can be expanded. For example, the command line could be typeset differently from the command output, or I may want to intercept a final \ to indent the subsequent lines, and so on...

In other words, I would like to preprocess the verbatim content of the environment before passing it to the actual lstlisting environment.

Is this even possible? How to do it?

• See tex.stackexchange.com/a/307130/36296 , the every listing line option may be helpful to get the $at every line. – user36296 Oct 6 '16 at 16:01 • @samcarter Wouldn't that put $ on every line, and not just the first line? – Teepeemm Oct 6 '16 at 16:06
• @Teepeemm You're right, I misunderstood your question. Sorry! – user36296 Oct 6 '16 at 16:34

This could quickly become too complicated for use, but I composed it to mention that the verbatimbox environments allow limited preprocessing of their content with an optional argument.

However, in this case, I am just using \active characters to intercept and test the input.

\documentclass{article}
\usepackage{verbatimbox,ifthen,xcolor}
\let\CatCode\catcode
\let\aCtive\active
\let\LCC c
\CatCodec=\aCtive %
\def c{\Ctest}
\CatCodec=11 %
\def\Ctest#1#2#3{%
\ifthenelse{\equal{#1#2}{at}}%
{\ifthenelse{\equal{#3}{:}}{\rmfamily\LCC#1#2#3}{\\$ \textcolor{red}{\LCC#1#2#3}}}%
{\LCC#1#2#3}%
}
\begin{document}
\begin{verbbox}
cat nothing > /dev/null
cat: nothing: No such file or directory
other stuff with a c in it
\end{verbbox}
verbatimbox without active c: \fbox{\theverbbox}

\CatCodec=\active
\begin{verbbox}
cat nothing > /dev/null
cat: nothing: No such file or directory
other stuff with a c in it
\end{verbbox}
\CatCodec=11
verbatimbox with active c: \fbox{\theverbbox}
\end{document}


• Thanks! Reading the documentation of verbatimbox, if I understand correctly, the customization is limited to the execution of some code before each line, right? So how to generically glob everything up to the next newline, process the line contents and then typeset the result? – gigabytes Oct 6 '16 at 16:29
• @gigabytes That interpretation is, unfortunately, correct. It can execute code prior to the verbatim line. To get inside the line, I can only think of the \active character approach to do so. – Steven B. Segletes Oct 6 '16 at 16:33
• Well I can immagine a command that can glob everything up to the first newline and process that. How could it be done? – gigabytes Oct 7 '16 at 17:25