2

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. – Steven B. Segletes Apr 14 '16 at 20:04
  • @StevenB.Segletes Can't as in "that's not even slightly possible"? – Holene Apr 14 '16 at 20:05
  • Correct, but there are other ways to skin the cat, depending on the requirements. – Steven B. Segletes Apr 14 '16 at 20:06
  • @StevenB.Segletes I love to skin cats – Holene Apr 14 '16 at 20:10
2

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}

enter image description here

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. – Steven B. Segletes Apr 14 '16 at 20:19
  • \texttt{} could suffice, but it would make it a nightmare to write something code-ish in the macro... – Holene Apr 14 '16 at 20:29
2

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}

enter image description here

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.