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 '19 at 3:02
  • You could use \texttt and `_’. – TeXnician Jun 20 '19 at 4:47
  • Did you consider the package newberbs? – egreg Jun 20 '19 at 12:05

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

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

\newcommand\x{y: \verb}

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.










enter image description here


This is a task for newverbs:




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

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


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.