1

Is there any way to define some custom command using the \verb|| environment? As an example, I want to write {\color{SteelBlue4} \verb|my_data.txt|} since using the _ will cause an error if I only use \texttt{}. So I tried writing \newcommand{\Rcode}[1]{{\color{SteelBlue4} \verb|#1|}}, but this does not work. Is there any way to do this, or is it just not possible?

  • See this TeX FAQ entry for an explanation on why this doesn't work. For your simple use case you could define \newcommand\Rcode{\lstinline[basicstyle=\color{...}]} using the listings package. – siracusa Jun 20 at 3:02
  • You could use \texttt and `_’. – TeXnician Jun 20 at 4:47
  • Did you consider the package newberbs? – egreg Jun 20 at 12:05
5

The problem with \verb is that it processes its input in a special way that prevents it from appearing inside of other commands or inside command arguments. For example, these two will give you an error

\newcommand\x{\verb|x|} % will only error once \x is used
\section{\verb|x|}

However, the command \verb itself is allowed to appear inside another command. This example is legal:

\newcommand\x{y: \verb}
\x|y|

That is because the argument of \verb does not appear inside of another command. Together with the knowledge that the font of \verb is determined by \verbatim@font, we can patch the \verb macro such that is accepts an optional argument and appends it to the font settings. With this we can then define the requested \Rcode command in the same manner. We pass the optional argument to \verb but the other argument we leave out and let \verb scan ahead by itself.

\documentclass{article}
\pagestyle{empty}
\usepackage[x11names]{xcolor}

\makeatletter

\let\normalverb=\verb
\let\normalverbatim@font=\verbatim@font

\renewcommand*\verb[1][]{%
    \expandafter\def\expandafter\verbatim@font\expandafter{\normalverbatim@font#1}%
    \normalverb
}

\makeatother

\newcommand{\Rcode}{\verb[\color{SteelBlue4}]}

\begin{document}

\Rcode|my_data|

\end{document}

enter image description here

1

This is a task for newverbs:

\documentclass{article}
\usepackage[x11names]{xcolor}
\usepackage{newverbs}

\newverbcommand{\Rcode}{\color{SteelBlue4}}{}

\begin{document}

Standard \verb+\verb+: \verb+my_data.txt+ and text after

With \verb+\Rcode+: \Rcode+my_data.txt+ and text after

\end{document}

enter image description here

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.