Parameter passing to \verb|| environment
I am surprised that it even compiled for you (your test example). On my installation
This is pdfTeX, Version
3.1415926-1.40.10 (Web2C 2009) entering extended mode
(./test.tex
LaTeX2e <2009/09/24>
Babel <v3.8l> and hyphenation patterns for english, usenglishmax, dumylang, noh yphenation, pinyin, bulgarian, russian, ukrainian, basque, french, loaded.
(/usr/share/texmf-dist/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texmf-dist/tex/latex/base/size10.clo))
(/usr/share/texmf-dist/tex/latex/graphics/color.sty
(/usr/share/texmf-dist/tex/latex/latexconfig/color.cfg)
(/usr/share/texmf-dist/tex/latex/graphics/dvips.def)
(/usr/share/texmf-dist/tex/latex/graphics/dvipsnam.def)) (./test.aux)
! LaTeX Error: \verb illegal in command argument.
See the LaTeX manual or LaTeX Companion for explanation. Type
H <return> for immediate help. ...
l.12 \result{red}{HI}
The reason is that \verb
is a very fragile command. The suggestion from the TeX faq I linked to is to replace \verb
by \texttt
, and when you type arguments to the \result
as you defined above, use \string
to escape the problematic characters. See also 'the string command'.
You could also define your own \verb
-like command using xparse
:
\documentclass{article}
\usepackage{xparse,xcolor}
\NewDocumentCommand\myvrb{O{blue}v}{%
\textcolor{#1}{\(>\)} \texttt{\footnotesize#2}}
\begin{document}
\myvrb|HI|
\myvrb[red]|HI|
\myvrb|&$#|
\end{document}
With a modicum of coercion, the verbatim package can be made to almost do what you want. The "almost" is because you have to use an environment instead of a command.
\documentclass{article}
\usepackage{verbatim}
\usepackage{xcolor}
\makeatletter
\newenvironment{result}[1]{%
\def\verbatim@processline{\the\verbatim@line\ }%
\def\@verbatim{\the\every@verbatim
\obeylines
\let\do\@makeother \dospecials
\verbatim@font
}%
\def\endverbatim{\endgroup}%
\noindent
{\color{#1}\texttt{>}}
\footnotesize
\verbatim}{\endverbatim}
\makeatother
\begin{document}
Here are your results:
\begin{result}{red}
greetings
\end{result}
\begin{result}{green}
A load of *@&$!)%*#$
\end{result}
\end{document}
In short, I looked a the definitions in the verbatim
package and stripped out everything that looked as though it might insert a newline, thus making the verbatim environment work on one line instead of several and meaning that it doesn't start or end with new lines. Then I put this inside a new environment so that the old \begin{verbatim} ... \end{verbatim}
construct still works as it should.
Caveat: Anything extra on the line \end{result}
gets discarded (LaTeX warns about this). So if you want to take out the \noindent
from the result
environment and have the input more like in the example in the question, the code will have to be:
\noindent\begin{result}{red}
greetings
\end{result}
\\
\begin{result}{green}
A load of *@&$!)%*#$
\end{result}