verbatim inside macro with color

Consider the following minimal non-working example (comment the line with the \test{..} to compile. I'd like to have a \verb+something+ inside my \test{} environment. How can I achieve that?

\documentclass{article}

\usepackage{xcolor,fancyvrb}
\newcommand{\test}[1]{{\color{blue}#1}}
\usepackage{siunitx,booktabs}
\begin{document}
This works \verb+\num{6.022e-23}+

\test{This is a test of a \verb+verb+}
\end{document}

• Can't place \verb inside a macro definition, or as an argument to one. Apr 14 '16 at 20:04
• @StevenB.Segletes Can't as in "that's not even slightly possible"? Apr 14 '16 at 20:05
• Correct, but there are other ways to skin the cat, depending on the requirements. Apr 14 '16 at 20:06
• @StevenB.Segletes I love to skin cats Apr 14 '16 at 20:10

You could use cprotect, but you should think twice before using \verb when, perhaps,\texttt might suffice.

\documentclass{article}

\usepackage{xcolor,cprotect}

\newcommand{\test}[1]{\textcolor{blue}{#1}}

\begin{document}

This works \verb+\num{6.022e-23}+

\cprotect\test{This is a test of a \verb+\num{6.022e-23}+}

\end{document}


If you have several appearances of \test containing \verb, you might want to make it automatically apply \cprotect:

\documentclass{article}

\usepackage{xcolor,cprotect}

\newcommand{\test}[1]{\textcolor{blue}{#1}}
\cMakeRobust\test

\begin{document}

This works \verb+\num{6.022e-23}+

\test{This is a test of a \verb+\num{6.022e-23}+}

\end{document}

• Was unaware of \cprotect. That's pretty cool. Apr 14 '16 at 20:19
• \texttt{} could suffice, but it would make it a nightmare to write something code-ish in the macro... Apr 14 '16 at 20:29

As I commented, \verb can neither appear in a macro definition nor argument.

However, depending on your need, this may suffice. One saves a verbbox in advance, and can pass that as an argument.

\documentclass{article}

\usepackage{xcolor,verbatimbox}
\newcommand{\test}[1]{{\color{blue}#1}}
\usepackage{siunitx,booktabs}
\begin{document}
This works \verb+\num{6.022e-23}+

\begin{verbbox}verb\end{verbbox}%
\test{This is a test of a \theverbbox}
\end{document}


If one wanted the verb in blue, then the verbbox can be saved as {\color{blue}\begin{verbbox}verb\end{verbbox}}%`.