[Tex/LaTex] Parameter passing to \verb|| environment


I happen to write the following code over and over again.

{\color{blue}\verb|>|} {\footnotesize\verb|HI|} 

So, I came up with the following code to make it a command.

{\color{#1}\verb|>|} {\footnotesize\verb|#2|} 

The problem is that the result is not what I expected, there are | characters attached.

What might be wrong? I need to have the verbatim environment kept as the result can contain some characters something like $, \


{\color{#1}$>$} {\footnotesize \verb|#2|} 


{\color{blue}\verb|>|} {\footnotesize\verb|HI|} 




  • For the original source, \verb|>| should have been $>$. I updated the source example.
  • Following Willie's answer, I modified the command

    \newcommand{\result}[2]{{\color{#1}$>$} {\footnotesize\texttt{#2}}}

It seems fine, but with multicols environment, the footnotesize font, gives some blank spaces before its printing of characters. I attach the screen capture and source code.

It seems that line break causes this problem, by adding \mbox inside the \texttt, I could remove the blank.

\newcommand{\result}[2]{{\color{#1}$>$} {\footnotesize\texttt{\mbox{#2}}}}

enter image description here


\newcommand{\result}[2]{{\color{#1}$>$} {\footnotesize\texttt{\mbox{#2}}}}
\newcommand{\resultp}[2]{{\color{#1}$>$} {\small\texttt{\mbox{#2}}}}


\noindent\result{green}{Welcome to my project! These are your args: (a b c)}\\ \result{green}{hello}\\ \result{green}{HI my\string_name}
\vskip 2ex
\noindent\resultp{green}{Welcome to my project! These are your args: (a b c)}\\ \resultp{green}{hello}\\ \resultp{green}{HI}


Best Answer

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 
LaTeX2e <2009/09/24> 
Babel <v3.8l> and hyphenation patterns for english, usenglishmax, dumylang, noh yphenation, pinyin, bulgarian, russian, ukrainian, basque, french, loaded. 
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class 
(/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'.